from __future__ import annotations

import json
import tempfile
import unittest
from http import HTTPStatus
from pathlib import Path
from unittest.mock import patch

from backend.features.heaven.engine import build_five_phase_field, hexagram_from_lines
from backend.features.heaven.http import HeavenHttpMixin
from backend.features.heaven.knowledge import (
    HeavenKnowledgeError,
    clear_heaven_knowledge_cache,
    prepare_heaven_context,
    resolve_heaven_knowledge_path,
    _knowledge_catalog,
)
from backend.features.heaven.six_yao import build_six_yao_chart


class HeavenKnowledgeTests(unittest.TestCase):
    def tearDown(self) -> None:
        clear_heaven_knowledge_cache()

    def test_catalog_loads_from_trusted_repo_file(self):
        clear_heaven_knowledge_cache()
        path = resolve_heaven_knowledge_path()
        catalog = _knowledge_catalog()
        self.assertTrue(path.is_file())
        self.assertEqual(path.name, "heaven_knowledge.json")
        self.assertTrue(str(catalog.get("version") or "").startswith("2026."))
        self.assertIn("zhouyi", catalog["sources"])
        self.assertIn("neijing", catalog["sources"])
        self.assertEqual(len(catalog["fortune"]["qi"]), 6)
        self.assertEqual(len(catalog["fortune"]["personal_relations"]), 10)

    def test_missing_knowledge_file_raises_chinese_structured_error(self):
        clear_heaven_knowledge_cache()
        missing = Path(tempfile.mkdtemp()) / "missing-heaven_knowledge.json"
        with patch(
            "backend.features.heaven.knowledge.KNOWLEDGE_FILE", missing
        ), patch(
            "backend.features.heaven.knowledge.KNOWLEDGE_SEED_FILE",
            missing.with_name("missing-seed.json"),
        ):
            with self.assertRaises(HeavenKnowledgeError) as raised:
                _knowledge_catalog()
        self.assertEqual(raised.exception.error_code, "heaven_knowledge_missing")
        self.assertIn("缺失", str(raised.exception))

    def test_corrupt_knowledge_json_raises_chinese_structured_error(self):
        clear_heaven_knowledge_cache()
        with tempfile.TemporaryDirectory() as temp_dir:
            broken = Path(temp_dir) / "heaven_knowledge.json"
            broken.write_text("{not-json", encoding="utf-8")
            with patch(
                "backend.features.heaven.knowledge.KNOWLEDGE_FILE", broken
            ), patch(
                "backend.features.heaven.knowledge.KNOWLEDGE_SEED_FILE",
                Path(temp_dir) / "unused-seed.json",
            ):
                with self.assertRaises(HeavenKnowledgeError) as raised:
                    _knowledge_catalog()
        self.assertEqual(raised.exception.error_code, "heaven_knowledge_invalid")
        self.assertIn("损坏", str(raised.exception))

    def test_interpret_http_returns_structured_chinese_error_for_missing_file(self):
        class FakeHandler(HeavenHttpMixin):
            def __init__(self) -> None:
                self.payload = None
                self.status = None
                self.application_service = type(
                    "Svc",
                    (),
                    {
                        "heaven_interpret": staticmethod(
                            lambda _body: (_ for _ in ()).throw(
                                HeavenKnowledgeError(
                                    "问天知识文件缺失：未找到 heaven_knowledge.json。",
                                    code="heaven_knowledge_missing",
                                )
                            )
                        )
                    },
                )()

            def read_json_body(self):
                return {"mode": "trend", "trade_date": "2026-08-04"}

            def send_json(self, payload, status=HTTPStatus.OK, headers=None):
                self.payload = payload
                self.status = status

        handler = FakeHandler()
        handler.heaven_interpret()
        self.assertEqual(handler.status, HTTPStatus.BAD_REQUEST)
        self.assertIn("缺失", handler.payload["error"])
        self.assertEqual(handler.payload["code"], "heaven_knowledge_missing")

    def test_interpret_http_returns_structured_chinese_error_for_corrupt_json(self):
        class FakeHandler(HeavenHttpMixin):
            def __init__(self) -> None:
                self.payload = None
                self.status = None
                self.application_service = type(
                    "Svc",
                    (),
                    {
                        "heaven_interpret": staticmethod(
                            lambda _body: (_ for _ in ()).throw(
                                HeavenKnowledgeError(
                                    "问天知识文件 JSON 损坏（heaven_knowledge.json），无法解析：第 1 行附近。",
                                    code="heaven_knowledge_invalid",
                                )
                            )
                        )
                    },
                )()

            def read_json_body(self):
                return {"mode": "trend", "trade_date": "2026-08-04"}

            def send_json(self, payload, status=HTTPStatus.OK, headers=None):
                self.payload = payload
                self.status = status

        handler = FakeHandler()
        handler.heaven_interpret()
        self.assertEqual(handler.status, HTTPStatus.BAD_REQUEST)
        self.assertIn("损坏", handler.payload["error"])
        self.assertEqual(handler.payload["code"], "heaven_knowledge_invalid")

    def test_seed_fallback_when_data_file_missing(self):
        clear_heaven_knowledge_cache()
        with tempfile.TemporaryDirectory() as temp_dir:
            seed = Path(temp_dir) / "seed.json"
            seed.write_text(
                json.dumps(
                    {
                        "version": "test-seed",
                        "sources": {"zhouyi": {"title": "周易"}},
                        "trend": {"method": "m", "rules": {"stable": "s", "single": "a", "multiple": "b"}},
                        "fortune": {},
                        "heart": {},
                    },
                    ensure_ascii=False,
                ),
                encoding="utf-8",
            )
            missing_data = Path(temp_dir) / "data-heaven_knowledge.json"
            with patch(
                "backend.features.heaven.knowledge.KNOWLEDGE_FILE", missing_data
            ), patch(
                "backend.features.heaven.knowledge.KNOWLEDGE_SEED_FILE", seed
            ):
                catalog = _knowledge_catalog()
        self.assertEqual(catalog["version"], "test-seed")

    def test_fortune_context_excludes_weighted_summary_and_adds_bounded_industry_symbols(self):
        field = build_five_phase_field("2026-08-04")
        prepared = prepare_heaven_context(
            "fortune",
            {
                "calendar_date": "20260804",
                "five_phase_field": field,
                "personal_profile": {},
            },
        )

        serialized = str(prepared["calculation"])
        self.assertNotIn("balance", serialized)
        self.assertNotIn("weights", serialized)
        self.assertNotIn("human_field", serialized)
        self.assertNotIn("sector_catalog", serialized)
        industry_symbols = prepared["calculation"]["industry_symbols"]
        self.assertTrue(industry_symbols)
        self.assertTrue(all(item["basis"] and item["industries"] for item in industry_symbols))
        self.assertIn(
            "fortune-industry-boundary",
            {record["id"] for record in prepared["knowledge"]["records"]},
        )
        self.assertEqual(prepared["knowledge"]["retrieval"], "deterministic-keyed")
        self.assertTrue(prepared["knowledge"]["records"])

    def test_fortune_personal_context_only_exposes_deterministic_stem_relations(self):
        field = build_five_phase_field("2026-08-04")
        prepared = prepare_heaven_context(
            "fortune",
            {
                "calendar_date": "20260804",
                "five_phase_field": field,
                "personal_profile": {
                    "day_master": {"stem": "丁", "element": "火", "strength": "偏弱"},
                    "current": {
                        "pillars": {"year": "丙午", "month": "乙未", "day": "庚戌"},
                        "ten_gods": {
                            "year": {"pillar": "丙午", "stem": "劫财", "branches": ["比肩"]},
                            "month": {"pillar": "乙未", "stem": "偏印", "branches": ["食神"]},
                            "day": {"pillar": "庚戌", "stem": "正财", "branches": ["伤官"]},
                        },
                    },
                },
            },
        )

        personal = prepared["calculation"]["personal"]
        self.assertEqual(personal["natal_day_master"], {"stem": "丁", "element": "火"})
        self.assertEqual(
            personal["today_relative_to_natal_day_master"]["stem_relations"],
            {"year": "劫财", "month": "偏印", "day": "正财"},
        )
        self.assertEqual(
            prepared["calculation"]["day_trigger"]["summary"],
            next(
                item["summary"]
                for item in field["framework"]["layers"]
                if item["id"] == "day"
            ),
        )
        record_ids = {record["id"] for record in prepared["knowledge"]["records"]}
        self.assertIn("fortune-personal-劫财", record_ids)
        self.assertIn("fortune-personal-偏印", record_ids)
        self.assertIn("fortune-personal-正财", record_ids)
        serialized = str(personal)
        self.assertNotIn("strength", serialized)
        self.assertNotIn("branches", serialized)

    def test_trend_retrieves_only_actual_moving_lines(self):
        hexagram = hexagram_from_lines([6, 7, 8, 9, 7, 8])
        prepared = prepare_heaven_context(
            "trend",
            {
                "data_trade_date": "20260804",
                "selected_focus": {
                    "sector": "银行",
                    "stock": {"code": "000001", "name": "平安银行", "change": 3.2},
                },
                "hexagram": hexagram,
                "movement": {},
            },
        )

        self.assertNotIn("selected_focus", prepared["calculation"])
        line_records = [
            record for record in prepared["knowledge"]["records"]
            if str(record.get("id") or "").startswith("zhouyi-line-")
        ]
        self.assertEqual([record["position"] for record in line_records], [1, 4])

    def test_heart_context_contains_question_chart_and_sources(self):
        values = [6, 7, 8, 9, 7, 8]
        prepared = prepare_heaven_context(
            "heart",
            {
                "question": "这笔交易最需要防范什么？",
                "question_preset": "trade",
                "hexagram": hexagram_from_lines(values),
                "six_yao": build_six_yao_chart(values, "2026-08-04T10:30:00+08:00"),
                "ritual": {},
            },
        )

        self.assertEqual(prepared["calculation"]["question_preset"], "trade")
        self.assertEqual(prepared["calculation"]["six_yao"]["method"], "京房纳甲·八宫世应")
        self.assertEqual(
            {source["id"] for source in prepared["knowledge"]["sources"]},
            {"zhouyi", "jingfang", "huozhulin", "zengshan"},
        )
        record_ids = {record["id"] for record in prepared["knowledge"]["records"]}
        self.assertIn("heart-self-response", record_ids)
        self.assertIn("heart-calendar", record_ids)
        self.assertIn("heart-movement", record_ids)
        self.assertIn("heart-relative-妻财", record_ids)
        self.assertIn("heart-timing-boundary", record_ids)


if __name__ == "__main__":
    unittest.main()
