"""I Ching trigrams and hexagrams module.

Provides fluent query interface for I Ching trigrams and hexagrams,
including Tarot correspondences and binary representations.

Usage:
    from letter.iChing import trigram, hexagram

    qian = trigram.trigram('Qian')
    creative = hexagram.hexagram(1)
"""

from typing import TYPE_CHECKING, Dict

from utils.query import CollectionAccessor

if TYPE_CHECKING:
    from tarot.attributes import Hexagram, Trigram


def _line_diagram_from_binary(binary: str) -> str:
    """Render a sideways ASCII diagram where top lines appear on the right."""
    if not binary:
        return ""
    cleaned = [bit for bit in binary if bit in {"0", "1"}]
    if not cleaned:
        return ""
    symbol_map = {"1": "|", "0": ":"}
    # Reverse so the right-most character represents the top line.
    return "".join(symbol_map[bit] for bit in reversed(cleaned))


class _Trigram:
    """Fluent query accessor for I Ching trigrams."""

    def __init__(self) -> None:
        self._initialized: bool = False
        self._trigrams: Dict[str, "Trigram"] = {}
        self.trigram = CollectionAccessor(self._get_trigrams)

    def _ensure_initialized(self) -> None:
        """Load trigrams on first access."""
        if self._initialized:
            return

        self._load_trigrams()
        self._initialized = True

    def _get_trigrams(self):
        self._ensure_initialized()
        return self._trigrams.copy()

    def _load_trigrams(self) -> None:
        """Load the eight I Ching trigrams."""
        from tarot.attributes import Trigram

        trigram_specs = [
            {
                "name": "Qian",
                "chinese": "乾",
                "pinyin": "Qián",
                "element": "Heaven",
                "attribute": "Creative",
                "binary": "111",
                "description": "Pure yang drive that initiates action.",
            },
            {
                "name": "Dui",
                "chinese": "兑",
                "pinyin": "Duì",
                "element": "Lake",
                "attribute": "Joyous",
                "binary": "011",
                "description": "Open delight that invites community.",
            },
            {
                "name": "Li",
                "chinese": "离",
                "pinyin": "Lí",
                "element": "Fire",
                "attribute": "Clinging",
                "binary": "101",
                "description": "Radiant clarity that adheres to insight.",
            },
            {
                "name": "Zhen",
                "chinese": "震",
                "pinyin": "Zhèn",
                "element": "Thunder",
                "attribute": "Arousing",
                "binary": "001",
                "description": "Sudden awakening that shakes stagnation.",
            },
            {
                "name": "Xun",
                "chinese": "巽",
                "pinyin": "Xùn",
                "element": "Wind",
                "attribute": "Gentle",
                "binary": "110",
                "description": "Penetrating influence that persuades subtly.",
            },
            {
                "name": "Kan",
                "chinese": "坎",
                "pinyin": "Kǎn",
                "element": "Water",
                "attribute": "Abysmal",
                "binary": "010",
                "description": "Depth, risk, and sincere feeling.",
            },
            {
                "name": "Gen",
                "chinese": "艮",
                "pinyin": "Gèn",
                "element": "Mountain",
                "attribute": "Stillness",
                "binary": "100",
                "description": "Grounded rest that establishes boundaries.",
            },
            {
                "name": "Kun",
                "chinese": "坤",
                "pinyin": "Kūn",
                "element": "Earth",
                "attribute": "Receptive",
                "binary": "000",
                "description": "Vast receptivity that nurtures form.",
            },
        ]
        self._trigrams = {}
        for spec in trigram_specs:
            name = spec.get("name")
            if not name:
                raise ValueError("Trigram spec missing 'name'")
            binary = spec.get("binary", "")
            self._trigrams[name.lower()] = Trigram(
                name=name,
                chinese_name=spec.get("chinese", ""),
                pinyin=spec.get("pinyin", ""),
                element=spec.get("element", ""),
                attribute=spec.get("attribute", ""),
                binary=binary,
                description=spec.get("description", ""),
                line_diagram=_line_diagram_from_binary(binary),
            )


class _Hexagram:
    """Fluent query accessor for I Ching hexagrams."""

    def __init__(self) -> None:
        self._initialized: bool = False
        self._hexagrams: Dict[int, "Hexagram"] = {}
        self.hexagram = CollectionAccessor(self._get_hexagrams)

    def _ensure_initialized(self) -> None:
        """Load hexagrams on first access."""
        if self._initialized:
            return

        self._load_hexagrams()
        self._initialized = True

    def _get_hexagrams(self):
        self._ensure_initialized()
        return self._hexagrams.copy()

    def _load_hexagrams(self) -> None:
        """Load all 64 I Ching hexagrams."""
        from tarot.attributes import Hexagram
        from tarot.card.data import CardDataLoader, calculate_digital_root

        # Ensure trigrams are loaded first
        trigram._ensure_initialized()

        # Load planets for hexagram correspondences
        loader = CardDataLoader()

        hex_specs = [
            {
                "number": 1,
                "name": "Creative Force",
                "chinese": "乾",
                "pinyin": "Qián",
                "judgement": "Initiative succeeds when anchored in integrity.",
                "image": "Heaven above and below mirrors unstoppable drive.",
                "upper": "Qian",
                "lower": "Qian",
                "keywords": "Leadership|Momentum|Clarity",
            },
            {
                "number": 2,
                "name": "Receptive Field",
                "chinese": "坤",
                "pinyin": "Kūn",
                "judgement": "Grounded support flourishes through patience.",
                "image": "Earth layered upon earth offers fertile space.",
                "upper": "Kun",
                "lower": "Kun",
                "keywords": "Nurture|Support|Yielding",
            },
            {
                "number": 3,
                "name": "Sprouting",
                "chinese": "屯",
                "pinyin": "Zhūn",
                "judgement": "Challenges at the start need perseverance.",
                "image": "Water over thunder shows storms that germinate seeds.",
                "upper": "Kan",
                "lower": "Zhen",
                "keywords": "Beginnings|Struggle|Resolve",
            },
            {
                "number": 4,
                "name": "Youthful Insight",
                "chinese": "蒙",
                "pinyin": "Méng",
                "judgement": "Ignorance yields to steady guidance.",
                "image": "Mountain above water signals learning via restraint.",
                "upper": "Gen",
                "lower": "Kan",
                "keywords": "Study|Mentorship|Humility",
            },
            {
                "number": 5,
                "name": "Waiting",
                "chinese": "需",
                "pinyin": "Xū",
                "judgement": "Hold position until nourishment arrives.",
                "image": "Water above heaven depicts clouds gathering provision.",
                "upper": "Kan",
                "lower": "Qian",
                "keywords": "Patience|Faith|Preparation",
            },
            {
                "number": 6,
                "name": "Conflict",
                "chinese": "訟",
                "pinyin": "Sòng",
                "judgement": "Clarity and fairness prevent escalation.",
                "image": "Heaven above water shows tension seeking balance.",
                "upper": "Qian",
                "lower": "Kan",
                "keywords": "Debate|Justice|Boundaries",
            },
            {
                "number": 7,
                "name": "Collective Force",
                "chinese": "師",
                "pinyin": "Shī",
                "judgement": "Coordinated effort requires disciplined leadership.",
                "image": "Earth over water mirrors troops marshaling supplies.",
                "upper": "Kun",
                "lower": "Kan",
                "keywords": "Discipline|Leadership|Community",
            },
            {
                "number": 8,
                "name": "Union",
                "chinese": "比",
                "pinyin": "Bǐ",
                "judgement": "Shared values attract loyal allies.",
                "image": "Water over earth highlights bonds formed through empathy.",
                "upper": "Kan",
                "lower": "Kun",
                "keywords": "Alliance|Affinity|Trust",
            },
            {
                "number": 9,
                "name": "Small Accumulating",
                "chinese": "小畜",
                "pinyin": "Xiǎo Chù",
                "judgement": "Gentle restraint nurtures gradual gains.",
                "image": "Wind over heaven indicates tender guidance on great power.",
                "upper": "Xun",
                "lower": "Qian",
                "keywords": "Restraint|Cultivation|Care",
            },
            {
                "number": 10,
                "name": "Treading",
                "chinese": "履",
                "pinyin": "Lǚ",
                "judgement": "Walk with awareness when near power.",
                "image": "Heaven over lake shows respect between ranks.",
                "upper": "Qian",
                "lower": "Dui",
                "keywords": "Conduct|Respect|Sensitivity",
            },
            {
                "number": 11,
                "name": "Peace",
                "chinese": "泰",
                "pinyin": "Tài",
                "judgement": "Harmony thrives when resources circulate freely.",
                "image": "Earth over heaven signals prosperity descending.",
                "upper": "Kun",
                "lower": "Qian",
                "keywords": "Harmony|Prosperity|Flourish",
            },
            {
                "number": 12,
                "name": "Standstill",
                "chinese": "否",
                "pinyin": "Pǐ",
                "judgement": "When channels close, conserve strength.",
                "image": "Heaven over earth reveals blocked exchange.",
                "upper": "Qian",
                "lower": "Kun",
                "keywords": "Stagnation|Reflection|Pause",
            },
            {
                "number": 13,
                "name": "Fellowship",
                "chinese": "同人",
                "pinyin": "Tóng Rén",
                "judgement": "Shared purpose unites distant hearts.",
                "image": "Heaven over fire shows clarity within community.",
                "upper": "Qian",
                "lower": "Li",
                "keywords": "Community|Shared Vision|Openness",
            },
            {
                "number": 14,
                "name": "Great Possession",
                "chinese": "大有",
                "pinyin": "Dà Yǒu",
                "judgement": "Generosity cements lasting influence.",
                "image": "Fire over heaven reflects radiance sustained by ethics.",
                "upper": "Li",
                "lower": "Qian",
                "keywords": "Wealth|Stewardship|Confidence",
            },
            {
                "number": 15,
                "name": "Modesty",
                "chinese": "謙",
                "pinyin": "Qiān",
                "judgement": "Balance is found by lowering the proud.",
                "image": "Earth over mountain reveals humility safeguarding strength.",
                "upper": "Kun",
                "lower": "Gen",
                "keywords": "Humility|Balance|Service",
            },
            {
                "number": 16,
                "name": "Enthusiasm",
                "chinese": "豫",
                "pinyin": "Yù",
                "judgement": "Inspired music rallies the people.",
                "image": "Thunder over earth depicts drums stirring hearts.",
                "upper": "Zhen",
                "lower": "Kun",
                "keywords": "Inspiration|Celebration|Momentum",
            },
            {
                "number": 17,
                "name": "Following",
                "chinese": "隨",
                "pinyin": "Suí",
                "judgement": "Adapt willingly to timely leadership.",
                "image": "Lake over thunder points to joyful allegiance.",
                "upper": "Dui",
                "lower": "Zhen",
                "keywords": "Adaptation|Loyalty|Flow",
            },
            {
                "number": 18,
                "name": "Repairing",
                "chinese": "蠱",
                "pinyin": "Gǔ",
                "judgement": "Address decay with responsibility and care.",
                "image": "Mountain over wind shows correction of lineages.",
                "upper": "Gen",
                "lower": "Xun",
                "keywords": "Restoration|Accountability|Healing",
            },
            {
                "number": 19,
                "name": "Approach",
                "chinese": "臨",
                "pinyin": "Lín",
                "judgement": "Leaders draw near to listen sincerely.",
                "image": "Earth over lake signifies compassion visiting the people.",
                "upper": "Kun",
                "lower": "Dui",
                "keywords": "Empathy|Guidance|Presence",
            },
            {
                "number": 20,
                "name": "Contemplation",
                "chinese": "觀",
                "pinyin": "Guān",
                "judgement": "Observation inspires ethical alignment.",
                "image": "Wind over earth is the elevated view of the sage.",
                "upper": "Xun",
                "lower": "Kun",
                "keywords": "Perspective|Ritual|Vision",
            },
            {
                "number": 21,
                "name": "Biting Through",
                "chinese": "噬嗑",
                "pinyin": "Shì Kè",
                "judgement": "Decisive action cuts through obstruction.",
                "image": "Fire over thunder shows justice enforced with clarity.",
                "upper": "Li",
                "lower": "Zhen",
                "keywords": "Decision|Justice|Resolve",
            },
            {
                "number": 22,
                "name": "Grace",
                "chinese": "賁",
                "pinyin": "Bì",
                "judgement": "Beauty adorns substance when humility remains.",
                "image": "Mountain over fire highlights poise and restraint.",
                "upper": "Gen",
                "lower": "Li",
                "keywords": "Aesthetics|Poise|Form",
            },
            {
                "number": 23,
                "name": "Splitting Apart",
                "chinese": "剝",
                "pinyin": "Bō",
                "judgement": "When decay spreads, strip away excess.",
                "image": "Mountain over earth signals outer shells falling.",
                "upper": "Gen",
                "lower": "Kun",
                "keywords": "Decline|Release|Truth",
            },
            {
                "number": 24,
                "name": "Return",
                "chinese": "復",
                "pinyin": "Fù",
                "judgement": "Cycles renew when rest follows completion.",
                "image": "Earth over thunder marks the turning of the year.",
                "upper": "Kun",
                "lower": "Zhen",
                "keywords": "Renewal|Rhythm|Faith",
            },
            {
                "number": 25,
                "name": "Innocence",
                "chinese": "無妄",
                "pinyin": "Wú Wàng",
                "judgement": "Sincerity triumphs over scheming.",
                "image": "Heaven over thunder shows spontaneous virtue.",
                "upper": "Qian",
                "lower": "Zhen",
                "keywords": "Authenticity|Spontaneity|Trust",
            },
            {
                "number": 26,
                "name": "Great Taming",
                "chinese": "大畜",
                "pinyin": "Dà Chù",
                "judgement": "Conserve strength until action serves wisdom.",
                "image": "Mountain over heaven portrays restraint harnessing power.",
                "upper": "Gen",
                "lower": "Qian",
                "keywords": "Discipline|Reserve|Mastery",
            },
            {
                "number": 27,
                "name": "Nourishment",
                "chinese": "頤",
                "pinyin": "Yí",
                "judgement": "Words and food alike must be chosen with care.",
                "image": "Mountain over thunder emphasizes mindful sustenance.",
                "upper": "Gen",
                "lower": "Zhen",
                "keywords": "Nutrition|Speech|Mindfulness",
            },
            {
                "number": 28,
                "name": "Great Exceeding",
                "chinese": "大過",
                "pinyin": "Dà Guò",
                "judgement": "Bearing heavy loads demands flexibility.",
                "image": "Lake over wind shows a beam bending before it breaks.",
                "upper": "Dui",
                "lower": "Xun",
                "keywords": "Weight|Adaptability|Responsibility",
            },
            {
                "number": 29,
                "name": "The Abyss",
                "chinese": "坎",
                "pinyin": "Kǎn",
                "judgement": "Repeated trials teach sincere caution.",
                "image": "Water over water is the perilous gorge.",
                "upper": "Kan",
                "lower": "Kan",
                "keywords": "Trial|Honesty|Depth",
            },
            {
                "number": 30,
                "name": "Radiance",
                "chinese": "離",
                "pinyin": "Lí",
                "judgement": "Clarity is maintained by tending the flame.",
                "image": "Fire over fire represents brilliance sustained through care.",
                "upper": "Li",
                "lower": "Li",
                "keywords": "Illumination|Culture|Attention",
            },
            {
                "number": 31,
                "name": "Influence",
                "chinese": "咸",
                "pinyin": "Xián",
                "judgement": "Sincere attraction arises from mutual respect.",
                "image": "Lake over mountain highlights responsive hearts.",
                "upper": "Dui",
                "lower": "Gen",
                "keywords": "Attraction|Mutuality|Sensitivity",
            },
            {
                "number": 32,
                "name": "Duration",
                "chinese": "恒",
                "pinyin": "Héng",
                "judgement": "Commitment endures when balanced.",
                "image": "Thunder over wind speaks of constancy amid change.",
                "upper": "Zhen",
                "lower": "Xun",
                "keywords": "Commitment|Consistency|Rhythm",
            },
            {
                "number": 33,
                "name": "Retreat",
                "chinese": "遯",
                "pinyin": "Dùn",
                "judgement": "Strategic withdrawal preserves integrity.",
                "image": "Heaven over mountain shows noble retreat.",
                "upper": "Qian",
                "lower": "Gen",
                "keywords": "Withdrawal|Strategy|Self-care",
            },
            {
                "number": 34,
                "name": "Great Power",
                "chinese": "大壯",
                "pinyin": "Dà Zhuàng",
                "judgement": "Strength must remain aligned with virtue.",
                "image": "Thunder over heaven affirms action matched with purpose.",
                "upper": "Zhen",
                "lower": "Qian",
                "keywords": "Power|Ethics|Momentum",
            },
            {
                "number": 35,
                "name": "Progress",
                "chinese": "晉",
                "pinyin": "Jìn",
                "judgement": "Advancement arrives through clarity and loyalty.",
                "image": "Fire over earth depicts dawn spreading across the plain.",
                "upper": "Li",
                "lower": "Kun",
                "keywords": "Advancement|Visibility|Service",
            },
            {
                "number": 36,
                "name": "Darkening Light",
                "chinese": "明夷",
                "pinyin": "Míng Yí",
                "judgement": "Protect the inner light when circumstances grow harsh.",
                "image": "Earth over fire shows brilliance concealed for safety.",
                "upper": "Kun",
                "lower": "Li",
                "keywords": "Protection|Subtlety|Endurance",
            },
            {
                "number": 37,
                "name": "Family",
                "chinese": "家人",
                "pinyin": "Jiā Rén",
                "judgement": "Clear roles nourish household harmony.",
                "image": "Wind over fire indicates rituals ordering the home.",
                "upper": "Xun",
                "lower": "Li",
                "keywords": "Home|Roles|Care",
            },
            {
                "number": 38,
                "name": "Opposition",
                "chinese": "睽",
                "pinyin": "Kuí",
                "judgement": "Recognize difference without hostility.",
                "image": "Fire over lake reflects contrast seeking balance.",
                "upper": "Li",
                "lower": "Dui",
                "keywords": "Contrast|Perspective|Tolerance",
            },
            {
                "number": 39,
                "name": "Obstruction",
                "chinese": "蹇",
                "pinyin": "Jiǎn",
                "judgement": "Turn hindrance into training.",
                "image": "Water over mountain shows difficult ascent.",
                "upper": "Kan",
                "lower": "Gen",
                "keywords": "Obstacle|Effort|Learning",
            },
            {
                "number": 40,
                "name": "Deliverance",
                "chinese": "解",
                "pinyin": "Xiè",
                "judgement": "Relief comes when knots are untied.",
                "image": "Thunder over water portrays release after storm.",
                "upper": "Zhen",
                "lower": "Kan",
                "keywords": "Release|Solution|Breath",
            },
            {
                "number": 41,
                "name": "Decrease",
                "chinese": "損",
                "pinyin": "Sǔn",
                "judgement": "Voluntary simplicity restores balance.",
                "image": "Mountain over lake shows graceful sharing of resources.",
                "upper": "Gen",
                "lower": "Dui",
                "keywords": "Simplicity|Offering|Balance",
            },
            {
                "number": 42,
                "name": "Increase",
                "chinese": "益",
                "pinyin": "Yì",
                "judgement": "Blessings multiply when shared.",
                "image": "Wind over thunder reveals generous expansion.",
                "upper": "Xun",
                "lower": "Zhen",
                "keywords": "Growth|Generosity|Opportunity",
            },
            {
                "number": 43,
                "name": "Breakthrough",
                "chinese": "夬",
                "pinyin": "Guài",
                "judgement": "Speak truth boldly to clear corruption.",
                "image": "Lake over heaven highlights decisive proclamation.",
                "upper": "Dui",
                "lower": "Qian",
                "keywords": "Resolution|Declaration|Courage",
            },
            {
                "number": 44,
                "name": "Encounter",
                "chinese": "姤",
                "pinyin": "Gòu",
                "judgement": "Unexpected influence requires discernment.",
                "image": "Heaven over wind shows potent visitors arriving.",
                "upper": "Qian",
                "lower": "Xun",
                "keywords": "Encounter|Discernment|Temptation",
            },
            {
                "number": 45,
                "name": "Gathering",
                "chinese": "萃",
                "pinyin": "Cuì",
                "judgement": "Unity grows when motive is sincere.",
                "image": "Lake over earth signifies assembly around shared cause.",
                "upper": "Dui",
                "lower": "Kun",
                "keywords": "Assembly|Devotion|Focus",
            },
            {
                "number": 46,
                "name": "Ascending",
                "chinese": "升",
                "pinyin": "Shēng",
                "judgement": "Slow steady progress pierces obstacles.",
                "image": "Earth over wind shows roots pushing upward.",
                "upper": "Kun",
                "lower": "Xun",
                "keywords": "Growth|Perseverance|Aspiration",
            },
            {
                "number": 47,
                "name": "Oppression",
                "chinese": "困",
                "pinyin": "Kùn",
                "judgement": "Constraints refine inner resolve.",
                "image": "Lake over water indicates fatigue relieved only by integrity.",
                "upper": "Dui",
                "lower": "Kan",
                "keywords": "Constraint|Endurance|Faith",
            },
            {
                "number": 48,
                "name": "The Well",
                "chinese": "井",
                "pinyin": "Jǐng",
                "judgement": "Communal resources must be maintained.",
                "image": "Water over wind depicts a well drawing fresh insight.",
                "upper": "Kan",
                "lower": "Xun",
                "keywords": "Resource|Maintenance|Depth",
            },
            {
                "number": 49,
                "name": "Revolution",
                "chinese": "革",
                "pinyin": "Gé",
                "judgement": "Change succeeds when timing and virtue align.",
                "image": "Lake over fire indicates shedding the old skin.",
                "upper": "Dui",
                "lower": "Li",
                "keywords": "Change|Timing|Renewal",
            },
            {
                "number": 50,
                "name": "The Vessel",
                "chinese": "鼎",
                "pinyin": "Dǐng",
                "judgement": "Elevated service transforms the culture.",
                "image": "Fire over wind depicts the cauldron that refines offerings.",
                "upper": "Li",
                "lower": "Xun",
                "keywords": "Service|Transformation|Heritage",
            },
            {
                "number": 51,
                "name": "Arousing Thunder",
                "chinese": "震",
                "pinyin": "Zhèn",
                "judgement": "Shock awakens the heart to reverence.",
                "image": "Thunder over thunder doubles the drumbeat of alertness.",
                "upper": "Zhen",
                "lower": "Zhen",
                "keywords": "Shock|Awakening|Movement",
            },
            {
                "number": 52,
                "name": "Still Mountain",
                "chinese": "艮",
                "pinyin": "Gèn",
                "judgement": "Cultivate stillness to master desire.",
                "image": "Mountain over mountain shows unmoving focus.",
                "upper": "Gen",
                "lower": "Gen",
                "keywords": "Stillness|Meditation|Boundaries",
            },
            {
                "number": 53,
                "name": "Gradual Development",
                "chinese": "漸",
                "pinyin": "Jiàn",
                "judgement": "Lasting progress resembles a tree growing rings.",
                "image": "Wind over mountain displays slow maturation.",
                "upper": "Xun",
                "lower": "Gen",
                "keywords": "Patience|Evolution|Commitment",
            },
            {
                "number": 54,
                "name": "Marrying Maiden",
                "chinese": "歸妹",
                "pinyin": "Guī Mèi",
                "judgement": "Adjust expectations when circumstances limit rank.",
                "image": "Thunder over lake spotlights unequal partnerships.",
                "upper": "Zhen",
                "lower": "Dui",
                "keywords": "Transition|Adaptation|Protocol",
            },
            {
                "number": 55,
                "name": "Abundance",
                "chinese": "豐",
                "pinyin": "Fēng",
                "judgement": "Radiant success must be handled with balance.",
                "image": "Thunder over fire illuminates the hall at noon.",
                "upper": "Zhen",
                "lower": "Li",
                "keywords": "Splendor|Responsibility|Timing",
            },
            {
                "number": 56,
                "name": "The Wanderer",
                "chinese": "旅",
                "pinyin": "Lǚ",
                "judgement": "Travel lightly and guard reputation.",
                "image": "Fire over mountain marks a traveler tending the campfire.",
                "upper": "Li",
                "lower": "Gen",
                "keywords": "Travel|Restraint|Awareness",
            },
            {
                "number": 57,
                "name": "Gentle Wind",
                "chinese": "巽",
                "pinyin": "Xùn",
                "judgement": "Persistent influence accomplishes what force cannot.",
                "image": "Wind over wind indicates subtle penetration.",
                "upper": "Xun",
                "lower": "Xun",
                "keywords": "Penetration|Diplomacy|Subtlety",
            },
            {
                "number": 58,
                "name": "Joyous Lake",
                "chinese": "兌",
                "pinyin": "Duì",
                "judgement": "Openhearted dialogue dissolves resentment.",
                "image": "Lake over lake celebrates shared delight.",
                "upper": "Dui",
                "lower": "Dui",
                "keywords": "Joy|Conversation|Trust",
            },
            {
                "number": 59,
                "name": "Dispersion",
                "chinese": "渙",
                "pinyin": "Huàn",
                "judgement": "Loosen rigid structures so spirit can move.",
                "image": "Wind over water shows breath dispersing fear.",
                "upper": "Xun",
                "lower": "Kan",
                "keywords": "Dissolve|Freedom|Relief",
            },
            {
                "number": 60,
                "name": "Limitation",
                "chinese": "節",
                "pinyin": "Jié",
                "judgement": "Clear boundaries enable real freedom.",
                "image": "Water over lake portrays calibrated vessels.",
                "upper": "Kan",
                "lower": "Dui",
                "keywords": "Boundaries|Measure|Discipline",
            },
            {
                "number": 61,
                "name": "Inner Truth",
                "chinese": "中孚",
                "pinyin": "Zhōng Fú",
                "judgement": "Trustworthiness unites disparate groups.",
                "image": "Wind over lake depicts resonance within the heart.",
                "upper": "Xun",
                "lower": "Dui",
                "keywords": "Sincerity|Empathy|Alignment",
            },
            {
                "number": 62,
                "name": "Small Exceeding",
                "chinese": "小過",
                "pinyin": "Xiǎo Guò",
                "judgement": "Attend to details when stakes are delicate.",
                "image": "Thunder over mountain reveals careful movement.",
                "upper": "Zhen",
                "lower": "Gen",
                "keywords": "Detail|Caution|Adjustment",
            },
            {
                "number": 63,
                "name": "After Completion",
                "chinese": "既濟",
                "pinyin": "Jì Jì",
                "judgement": "Success endures only if vigilance continues.",
                "image": "Water over fire displays balance maintained through work.",
                "upper": "Kan",
                "lower": "Li",
                "keywords": "Completion|Maintenance|Balance",
            },
            {
                "number": 64,
                "name": "Before Completion",
                "chinese": "未濟",
                "pinyin": "Wèi Jì",
                "judgement": "Stay attentive as outcomes crystallize.",
                "image": "Fire over water illustrates the final push before harmony.",
                "upper": "Li",
                "lower": "Kan",
                "keywords": "Transition|Focus|Preparation",
            },
        ]
        planet_cycle = ["Sun", "Moon", "Mercury", "Venus", "Mars", "Jupiter", "Saturn", "Earth"]
        self._hexagrams = {}
        for spec in hex_specs:
            number = spec.get("number")
            name = spec.get("name")
            upper_name = spec.get("upper")
            lower_name = spec.get("lower")
            if number is None or not name or not upper_name or not lower_name:
                continue
            upper = trigram._trigrams.get(upper_name.lower())
            lower = trigram._trigrams.get(lower_name.lower())
            if upper is None or lower is None:
                continue
            assoc_number = loader._numbers.get(calculate_digital_root(number))
            planet_name = spec.get("planet") or planet_cycle[(number - 1) % len(planet_cycle)]
            planet = loader._planets.get(planet_name.lower()) if planet_name else None
            keywords_field = spec.get("keywords")
            keywords = keywords_field.split("|") if keywords_field else []
            line_diagram = _line_diagram_from_binary(upper.binary + lower.binary)
            self._hexagrams[number] = Hexagram(
                number=number,
                name=name,
                chinese_name=spec.get("chinese", ""),
                pinyin=spec.get("pinyin", ""),
                judgement=spec.get("judgement", ""),
                image=spec.get("image", ""),
                upper_trigram=upper,
                lower_trigram=lower,
                keywords=keywords,
                associated_number=assoc_number,
                planetary_influence=planet,
                line_diagram=line_diagram,
            )


# Create singleton instances
trigram = _Trigram()
hexagram = _Hexagram()
