from __future__ import annotations

import unittest

from backend.features.heaven.engine import build_five_phase_field, hexagram_from_lines
from backend.features.heaven.knowledge import prepare_heaven_context
from backend.features.heaven.six_yao import build_six_yao_chart


class HeavenKnowledgeTests(unittest.TestCase):
    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()
