"""Card details and interpretations for all 78 Tarot cards.

This module provides interpretive data (explanations, keywords, guidance) for cards.
Registry is keyed by card position (1-78), independent of deck-specific names.

Deck order: Cups (1-14), Pentacles (15-28), Swords (29-42), 
           Major Arcana (43-64), Wands (65-78)

Usage:
    from tarot.card.details import CardDetailsRegistry
    
    registry = CardDetailsRegistry()
    details = registry.get_by_position(44)  # Get details for card at position 44
    
    # Or load into a card object:
    from tarot.deck import Deck
    deck = Deck()
    card = deck.cards[43]  # Card at position 44 (0-indexed)
    registry.load_into_card(card)
"""

from typing import TYPE_CHECKING, Any, Dict, Optional

if TYPE_CHECKING:
    from tarot.deck import Card


class CardDetailsRegistry:
    """Registry for storing interpretive data for all 78 Tarot cards.
    
    Uses card position (1-78) as the unique identifier, independent of deck names.
    This allows the same card details to apply across different deck variants.
    
    Deck order:
    - 1-14: Cups (Ace, Ten, 2-9, Knight, Prince, Princess, Queen)
    - 15-28: Pentacles (same structure)
    - 29-42: Swords (same structure)
    - 43-64: Major Arcana (Fool through Universe)
    - 65-78: Wands (same structure)
    """
    
    def __init__(self) -> None:
        """Initialize the card details registry with interpretive data."""
        self._details: Dict[str, Dict[str, Any]] = self._build_registry()
        # Map card positions (1-78) to registry keys
        self._position_map = self._build_position_map()
    
    @staticmethod
    def key_to_roman(key: int) -> str:
        """
        Convert a numeric key to Roman numerals.
        
        Args:
            key: The numeric key (0-21 for major arcana)
            
        Returns:
            Roman numeral representation (e.g., 21 -> "XXI", 0 -> "o")
        """
        # Special case: 0 -> "o" (letter O for The Fool)
        if key == 0:
            return "o"
        
        val = [
            1000, 900, 500, 400,
            100, 90, 50, 40,
            10, 9, 5, 4,
            1
        ]
        syms = [
            "M", "CM", "D", "CD",
            "C", "XC", "L", "XL",
            "X", "IX", "V", "IV",
            "I"
        ]
        roman_num = ''
        i = 0
        while key > 0:
            for _ in range(key // val[i]):
                roman_num += syms[i]
                key -= val[i]
            i += 1
        return roman_num if roman_num else "o"
    
    def _build_position_map(self) -> Dict[int, str]:
        """
        Build a mapping from card position (1-78) to registry key.
        
        Returns:
            Dictionary mapping position to registry key
        """
        position_map = {}
        
        # Positions 1-14: Cups (Ace, Ten, 2-9, Knight, Prince, Princess, Queen)
        cups_names = ["Ace of Cups", "Ten of Cups", "Two of Cups", "Three of Cups",
                      "Four of Cups", "Five of Cups", "Six of Cups", "Seven of Cups",
                      "Eight of Cups", "Nine of Cups", "Knight of Cups", "Prince of Cups",
                      "Princess of Cups", "Queen of Cups"]
        for pos, name in enumerate(cups_names, start=1):
            position_map[pos] = name
        
        # Positions 15-28: Pentacles (same structure)
        pentacles_names = ["Ace of Pentacles", "Ten of Pentacles", "Two of Pentacles", "Three of Pentacles",
                           "Four of Pentacles", "Five of Pentacles", "Six of Pentacles", "Seven of Pentacles",
                           "Eight of Pentacles", "Nine of Pentacles", "Knight of Pentacles", "Prince of Pentacles",
                           "Princess of Pentacles", "Queen of Pentacles"]
        for pos, name in enumerate(pentacles_names, start=15):
            position_map[pos] = name
        
        # Positions 29-42: Swords (same structure)
        swords_names = ["Ace of Swords", "Ten of Swords", "Two of Swords", "Three of Swords",
                        "Four of Swords", "Five of Swords", "Six of Swords", "Seven of Swords",
                        "Eight of Swords", "Nine of Swords", "Knight of Swords", "Prince of Swords",
                        "Princess of Swords", "Queen of Swords"]
        for pos, name in enumerate(swords_names, start=29):
            position_map[pos] = name
        
        # Positions 43-64: Major Arcana (mapped to Roman numerals)
        major_arcana_keys = ["o", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
                             "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX",
                             "XX", "XXI"]
        for pos, key in enumerate(major_arcana_keys, start=43):
            position_map[pos] = key
        
        # Positions 65-78: Wands (same structure)
        wands_names = ["Ace of Wands", "Ten of Wands", "Two of Wands", "Three of Wands",
                       "Four of Wands", "Five of Wands", "Six of Wands", "Seven of Wands",
                       "Eight of Wands", "Nine of Wands", "Knight of Wands", "Prince of Wands",
                       "Princess of Wands", "Queen of Wands"]
        for pos, name in enumerate(wands_names, start=65):
            position_map[pos] = name
        
        return position_map
    
    def get_by_position(self, position: int) -> Optional[Dict[str, Any]]:
        """
        Get details for a card by its position (1-78).
        
        Args:
            position: Card position (1-78)
            
        Returns:
            Dictionary containing card details, or None if not found
        """
        registry_key = self._position_map.get(position)
        if registry_key is None:
            return None
        return self._details.get(registry_key)
    
    def _build_registry(self) -> Dict[str, Dict[str, Any]]:
        """Build the interpretive data registry (card structure comes from Deck).
        
        Stores only unique interpretive data (explanation, keywords, guidance).
        Card names and structure are sourced from Deck for DRY compliance.
        """
        return {
            # Major Arcana (0-21) - Interpretive data only
            "o": {
                "explanation": "The Fool represents new beginnings, innocence, and spontaneity. This card signifies a fresh start or embarking on a new journey with optimism and faith.",
                "interpretation": "Beginning of the Great Work, innocence; a fool for love; divine madness. Reason is transcended. Take the leap. Gain or loss through foolish actions.",
                "keywords": ["new beginnings", "innocence", "faith", "spontaneity", "potential"],
                "reversed_keywords": ["recklessness", "naivety", "poor judgment", "folly"],
                "guidance": "Trust in the unfolding of your path. Embrace new opportunities with awareness and openness.",
            },
            "I": {
                "explanation": "The Magician embodies manifestation, resourcefulness, and personal power. This card shows mastery of skills and the ability to turn ideas into reality.",
                "interpretation": "Communication; Conscious Will; the process of continuous creation; ambiguity; deceptionl Things may not be as they appear. Concentration, meditation; mind used to direct the Will. Manipulation; crafty maneuverings.",
                "keywords": ["manifestation", "resourcefulness", "power", "inspired action", "concentration"],
                "reversed_keywords": ["manipulation", "poor planning", "untapped talents", "lack of direction"],
                "guidance": "Focus your energy and intention on what you want to manifest. You have the tools and talents you need.",
            },
            "II": {
                "explanation": "The High Priestess represents intuition, sacred knowledge, and the subconscious mind. She embodies mystery and inner wisdom.",
                "interpretation": "Symbol of highest initiation; link between the archetypal and Formative Worlds. An initiatrixl Wooing by enchantment. possibility. The Idea behind the Form. Fluctuationl Time may not be right for a decision concerning mundane matters.",
                "keywords": ["intuition", "sacred knowledge", "divine feminine", "the subconscious", "mystery"],
                "reversed_keywords": ["hidden information", "silence", "disconnection from intuition", "superficiality"],
                "guidance": "Listen to your inner voice. The answers you seek lie within. Trust the wisdom of your intuition.",
            },
            "III": {
                "explanation": "The Empress symbolizes abundance, fertility, and nurturing energy. She represents creativity, sensuality, and the power of manifestation through nurturing.",
                "interpretation": "The Holy Grail. love unites the Will. Love; beauty; friendship; success; passive balance. The feminine point of view. The door is open. Disregard the details and concentrate on the big picture.",
                "keywords": ["abundance", "fertility", "femininity", "beauty", "nature", "creativity"],
                "reversed_keywords": ["dependency", "creative block", "neediness", "underdevelopment"],
                "guidance": "Nurture yourself and others. Allow yourself to enjoy the fruits of your labor and appreciate beauty.",
            },
            "IV": {
                "explanation": "The Emperor represents authority, leadership, and established power. He embodies structure, discipline, and protection through strength and control.",
                "interpretation": "Creative wisdom radiating upon the organized man and woman. Domination after conquest; quarrelsomeness; paternal love; ambition. Thought ruled by creative, masculine, fiery energy. Stubbornness; war; authority; energy in its most temporal form. Swift immpermaent action over confidence.",
                "keywords": ["authority", "leadership", "power", "structure", "protection", "discipline"],
                "reversed_keywords": ["weakness", "ineffectual leadership", "lack of discipline", "tyranny"],
                "guidance": "Step into your power with confidence. Establish clear boundaries and structure. Lead by example.",
            },
            "V": {
                "explanation": "The Hierophant represents tradition, conventional wisdom, and spiritual authority. This card embodies education, ceremony, and moral values.",
                "interpretation": "The Holy Guardian Angel. The uniting of t hat which is above with that which is below. Love is indicated, but the nature of that love is not yet to be revealed. Inspiration; teaching; organization; discipline; strength; endurance; toil; help from superiors.",
                "keywords": ["tradition", "spirituality", "wisdom", "ritual", "morality", "ethics"],
                "reversed_keywords": ["rebellion", "unconventionality", "questioning authority", "dogmatism"],
                "guidance": "Seek guidance from established wisdom. Respect traditions while finding your own spiritual path.",
            },
            "VI": {
                "explanation": "The Lovers represents relationships, values alignment, and the union of opposites. It signifies choice, intimacy, and deep connection.",
                "interpretation": "Intuition. Be open to your own inner voice. A well-intended, arranged marriage. An artificial union. The need to make a choice with awareness of consequences union; analysis followed by synthesis; indecision; instability; superficiality.",
                "keywords": ["relationships", "love", "union", "values", "choice", "alignment"],
                "reversed_keywords": ["disharmony", "misalignment", "conflict", "communication breakdown"],
                "guidance": "Choose with your heart aligned with your values. Deep connection requires vulnerability and honesty.",
            },
            "VII": {
                "explanation": "The Chariot embodies willpower, determination, and control through focused intention. It represents triumph through discipline and forward momentum.",
                "interpretation": "Light in the darkness. The burden you carry may be the Holy Grail. Faithfulness; hope; obedience; a protective relationship; firm, even violent adherance to dogma or tradition. Glory; riches; englightened civilization; victory; triumph; chain of command.",
                "keywords": ["determination", "willpower", "control", "momentum", "victory", "focus"],
                "reversed_keywords": ["lack of control", "haste", "resistance", "moving backward"],
                "guidance": "Take the reins of your life. Move forward with determination and clear direction. You have the power.",
            },
            "VIII": {
                "explanation": "Strength represents inner power, courage, and compassion. It shows mastery through gentleness and the ability to face challenges with calm confidence.",
                "interpretation": "Equilibrium; karmic law; the dance of life; all possibilities. The woman satisfied. Balance; weigh each thought against its opposite. Lawsuits; treaties. Pause and look before you leap.",
                "keywords": ["strength", "courage", "patience", "compassion", "control", "confidence"],
                "reversed_keywords": ["weakness", "self-doubt", "lack of composure", "poor control"],
                "guidance": "True strength comes from within. Face challenges with courage and compassion for yourself and others.",
            },
            "IX": {
                "explanation": "The Hermit represents introspection, spiritual seeking, and inner guidance. This card embodies solitude, wisdom gained through reflection, and self-discovery.",
                "interpretation": "Divine seed of all things. By silence comes inspiration and wisdom. Wandering alone; temporary solitude; creative contemplation; a virgin. Retirement from involvement in current events.",
                "keywords": ["introspection", "spiritual seeking", "inner light", "wisdom", "solitude", "truth"],
                "reversed_keywords": ["loneliness", "isolation", "lost", "paranoia", "disconnection"],
                "guidance": "Take time for introspection and self-discovery. Your inner light guides your path. Seek solitude for wisdom.",
            },
            "X": {
                "explanation": "The Wheel of Fortune represents cycles, destiny, and the turning points of life. It embodies luck, karma, and the natural ebb and flow of existence.",
                "interpretation": "Continual change. In the midst of revolving phenomena, reaach joyously the motionless center. Carefree love; wanton pleasure; amusement; fun; change of fortune, usually good.",
                "keywords": ["fate", "destiny", "cycles", "fortune", "karma", "turning point"],
                "reversed_keywords": ["bad luck", "resistance to change", "broken cycles", "misfortune"],
                "guidance": "Trust in the cycles of life. What goes up must come down. Embrace change as part of your journey.",
            },
            "XI": {
                "explanation": "Justice represents fairness, truth, and balance. It embodies accountability, clear judgment, and the consequences of actions both past and present.",
                "interpretation": "Understanding; the Will of New Aeon; passion; sense smitten with ecstasy. let love devour all. Energy independent of reason. Strength; courage; utilization of magical power.",
                "keywords": ["justice", "fairness", "truth", "cause and effect", "balance", "accountability"],
                "reversed_keywords": ["injustice", "bias", "lack of accountability", "dishonesty"],
                "guidance": "Seek the truth and act with fairness. Take responsibility for your actions. Balance is key.",
            },
            "XII": {
                "explanation": "The Hanged Man represents suspension, letting go, and seeing things from a new perspective. It embodies surrender, pause, and gaining wisdom through sacrifice.",
                "interpretation": "Redemption, sacrifice, annihilation in the beloved; martyrdom; loss; torment; suspension; death; suffering.",
                "keywords": ["suspension", "restriction", "letting go", "new perspective", "surrender", "pause"],
                "reversed_keywords": ["resistance", "stalling", "unwillingness to change", "impatience"],
                "guidance": "Pause and reflect. What are you holding onto? Surrender control and trust the process.",
            },
            "XIII": {
                "explanation": "Death represents transformation, endings, and new beginnings. This card embodies major life transitions, the release of the old, and inevitable change.",
                "interpretation": "End of cycle; transformation; raw sexuality. Sex is death. Stress becomes intolerable. Any change is welcome. Time; age; unexpected change; death.",
                "keywords": ["transformation", "transition", "endings", "beginnings", "change", "acceptance"],
                "reversed_keywords": ["resistance to change", "stagnation", "missed opportunity", "delay"],
                "guidance": "Release what no longer serves you. Transformation is inevitable. Trust in the cycle of death and rebirth.",
            },
            "XIV": {
                "explanation": "Temperance represents balance, moderation, and harmony. It embodies blending of opposites, inner peace through balance, and finding your rhythm.",
                "interpretation": "Transmutation through union of opposites. A perfect marriage exalts and transforms each partner. The scientific method. Success follows complex maneuvers.",
                "keywords": ["balance", "moderation", "harmony", "patience", "timing", "peace"],
                "reversed_keywords": ["imbalance", "excess", "conflict", "intemperance", "discord"],
                "guidance": "Seek balance in all things. Blend opposing forces. Find your rhythm through moderation and patience.",
            },
            "XV": {
                "explanation": "The Devil represents bondage, materialism, and shadow aspects of self. It embodies addictions, illusions, and the consequences of giving away personal power.",
                "interpretation": "Thou hast no right but to do thy will. Obession; temptation; ecstasy found in every phenomenon; creative action, yet sublimely careless of result; unscrupulous ambition; strength.",
                "keywords": ["bondage", "materialism", "playfulness", "shadow self", "sexuality", "excess"],
                "reversed_keywords": ["freedom", "detachment", "reclaiming power", "breaking free"],
                "guidance": "Examine what binds you. Acknowledge your shadow. You hold the key to your own freedom.",
            },
            "XVI": {
                "explanation": "The Tower represents sudden disruption, revelation, and breakthrough through crisis. It embodies sudden change, truth revealed, and necessary destruction.",
                "interpretation": "Escape from the prison of organized life; renunciation of love; quarreling. Plans are destroyed. War; danger; sudden death.",
                "keywords": ["sudden change", "upheaval", "revelation", "breakdown", "breakthrough", "chaos"],
                "reversed_keywords": ["resistance to change", "averted crisis", "delay", "stagnation"],
                "guidance": "Crisis brings clarity. Though change is sudden and jarring, it clears away the false and brings truth.",
            },
            "XVII": {
                "explanation": "The Star represents hope, guidance, and inspiration. It embodies clarity of purpose, spiritual insight, and the light that guides your path forward.",
                "interpretation": "Clairvoyance; visions; drams; hope; love; yearning; realization of inexhaustible possibilities; dreaminess; unexpected help; renewal.",
                "keywords": ["hope", "faith", "inspiration", "vision", "guidance", "spirituality"],
                "reversed_keywords": ["hopelessness", "despair", "lack of direction", "lost", "obscured"],
                "guidance": "Let your inner light shine. Trust in your vision. Hope and guidance light your path forward.",
            },
            "XVIII": {
                "explanation": "The Moon represents illusion, intuition, and the subconscious mind. It embodies mystery, dreams, and navigating by inner knowing rather than sight.",
                "interpretation": "The Dark night of the soul; deception; falsehood; illusion; madness; the threshold of significant change.",
                "keywords": ["illusion", "intuition", "uncertainty", "subconscious", "dreams", "mystery"],
                "reversed_keywords": ["clarity", "truth revealed", "release from illusion", "awakening"],
                "guidance": "Trust your intuition to navigate mystery. What appears illusory contains deeper truths worth exploring.",
            },
            "XIX": {
                "explanation": "The Sun represents joy, clarity, and vitality. It embodies success, positive energy, and the radiance of authentic self-expression.",
                "interpretation": "Lord of the New Aeon. Spiritual emancipation. Pleasure; shamelessness; vanity; frankness. Freedom brings sanity. Glory; riches; enlightened civilization.",
                "keywords": ["success", "joy", "clarity", "vitality", "warmth", "authenticity"],
                "reversed_keywords": ["temporary darkness", "lost vitality", "setback", "sadness"],
                "guidance": "Celebrate your success. Let your authentic self shine. Joy and clarity light your way.",
            },
            "XX": {
                "explanation": "Judgement represents awakening, calling, and significant decisions. It embodies reckoning, rebirth, and responding to a higher calling.",
                "interpretation": "Let every act be an act of Worship; let every act be an act of Love. Final decision; judgement. Learn from the past. Prepare for the future.",
                "keywords": ["awakening", "calling", "judgment", "rebirth", "evaluation", "absolution"],
                "reversed_keywords": ["doubt", "self-doubt", "harsh judgment", "reluctance to change"],
                "guidance": "Answer your higher calling. Evaluate with compassion. A significant awakening or decision awaits.",
            },
            "XXI": {
                "explanation": "The World represents completion, wholeness, and fulfillment. It embodies the end of a cycle, achievement of goals, and a sense of unity.",
                "interpretation": "Completion of the Greatk Work; patience; perseverance; stubbornness; serious meditation. Work accomplished.",
                "keywords": ["completion", "fulfillment", "wholeness", "travel", "unity", "achievement"],
                "reversed_keywords": ["incomplete", "blocked", "separation", "seeking closure"],
                "guidance": "A significant cycle completes. You have achieved wholeness. Yet every ending is a new beginning.",
            },
            
            # Minor Arcana - Swords
            "Ace of Swords": {
                "explanation": "The Ace of Swords represents clarity, breakthrough, and new ideas. It embodies truth emerging, mental clarity, and the power of honest communication.",
                "interpretation": "New idea or perspective, clarity and truth, breakthrough thinking, mental clarity",
                "keywords": ["breakthrough", "clarity", "truth", "new ideas", "communication"],
                "reversed_keywords": ["confusion", "unclear communication", "hidden truth", "mental fog"],
                "guidance": "A breakthrough arrives. Speak your truth with clarity. Mental clarity reveals new possibilities.",
            },
            "Two of Swords": {
                "explanation": "The Two of Swords represents stalemate, difficult choices, and mental struggle. It embodies indecision, conflicting information, and the need for perspective.",
                "interpretation": "Stalemate and indecision, difficult choices ahead, conflicting perspectives, mental struggle",
                "keywords": ["stalemate", "indecision", "confusion", "difficult choice", "standoff"],
                "reversed_keywords": ["clarity emerging", "decision made", "moving forward", "resolution"],
                "guidance": "Step back from the conflict. You need more information or perspective before deciding.",
            },
            "Three of Swords": {
                "explanation": "The Three of Swords represents heartbreak, difficult truths, and mental anguish. It embodies challenging communication, painful revelations, and clarity that hurts.",
                "interpretation": "Difficult truths and heartbreak, communication challenges, mental anguish, clarity through pain",
                "keywords": ["heartbreak", "sorrow", "difficult truth", "mental anguish", "separation"],
                "reversed_keywords": ["healing", "moving forward", "forgiveness", "reconciliation"],
                "guidance": "Difficult truths are emerging. Allow yourself to feel the pain. Healing follows acknowledgment.",
            },
            "Four of Swords": {
                "explanation": "The Four of Swords represents rest, recovery, and mental respite. It embodies the need for pause, recuperation, and gathering strength.",
                "interpretation": "Rest and recovery, pause and contemplation, gathering strength, needed respite",
                "keywords": ["rest", "pause", "recovery", "contemplation", "respite"],
                "reversed_keywords": ["restlessness", "stress", "unwillingness to rest", "agitation"],
                "guidance": "Take time to rest and recover. Your mind and spirit need respite. Gather your strength.",
            },
            "Five of Swords": {
                "explanation": "The Five of Swords represents conflict, victory at a cost, and difficult truths after battle. It embodies competition with consequences and the emptiness of winning wrongly.",
                "interpretation": "Conflict and competition, pyrrhic victory, harsh truths, aftermath of conflict",
                "keywords": ["conflict", "defeat", "victory at cost", "awkwardness", "tension"],
                "reversed_keywords": ["reconciliation", "resolution", "forgiveness", "peace"],
                "guidance": "Sometimes victory costs more than it's worth. Seek reconciliation over conquest.",
            },
            "Six of Swords": {
                "explanation": "The Six of Swords represents moving forward, healing journey, and leaving troubles behind. It embodies transition, mental resolution, and the path to better days.",
                "interpretation": "Moving forward and transition, leaving trouble behind, journey and travel, mental resolution",
                "keywords": ["transition", "healing journey", "moving forward", "travel", "freedom"],
                "reversed_keywords": ["stuck", "resistance to change", "delays", "unresolved issues"],
                "guidance": "A journey of healing begins. Move forward. Leave the past behind. Better days await.",
            },
            "Seven of Swords": {
                "explanation": "The Seven of Swords represents deception, cunning, and strategic retreat. It embodies hidden agendas, betrayal, and escape from difficult situations.",
                "interpretation": "Deception and cunning, hidden agendas, strategic retreat, betrayal or self-deception",
                "keywords": ["deception", "cunning", "betrayal", "hidden agenda", "strategy"],
                "reversed_keywords": ["coming clean", "honesty", "truth revealed", "facing consequences"],
                "guidance": "Look for hidden truths. Deception may be at play. Where are you deceiving yourself?",
            },
            "Eight of Swords": {
                "explanation": "The Eight of Swords represents restriction, bondage, and self-imposed limitations. It embodies feeling trapped, mental imprisonment, and powerlessness.",
                "interpretation": "Restriction and bondage, self-imposed limitations, feeling trapped, helplessness",
                "keywords": ["bondage", "restriction", "trapped", "helplessness", "powerlessness"],
                "reversed_keywords": ["freedom", "release", "empowerment", "breaking free"],
                "guidance": "You have more power than you believe. The restrictions may be self-imposed. Free yourself.",
            },
            "Nine of Swords": {
                "explanation": "The Nine of Swords represents anxiety, nightmares, and mental torment. It embodies overthinking, worry, and the burden of negative thoughts.",
                "interpretation": "Anxiety and worry, nightmares and turmoil, overthinking, mental burden",
                "keywords": ["anxiety", "worry", "nightmares", "overthinking", "despair"],
                "reversed_keywords": ["relief", "healing", "moving past", "mental clarity"],
                "guidance": "Your mind is your greatest torment. Seek support. This darkness passes. Morning follows night.",
            },
            "Ten of Swords": {
                "explanation": "The Ten of Swords represents complete mental/emotional defeat, rock bottom, and the end of suffering. It embodies the culmination of difficulty and the promise of renewal.",
                "interpretation": "Defeat and rock bottom, end of suffering, difficult conclusion, release from burden",
                "keywords": ["defeat", "rock bottom", "ending", "relief", "betrayal"],
                "reversed_keywords": ["recovery", "beginning again", "healing", "hope"],
                "guidance": "The worst has passed. You've hit bottom. From here, only recovery is possible.",
            },
            "Page of Swords": {
                "explanation": "The Page of Swords represents curious inquiry, new ideas, and youthful intellectual energy. It embodies investigation, learning, and the drive to understand.",
                "interpretation": "Curiosity and new learning, investigation and inquiry, youthful energy, intellectual development",
                "keywords": ["curiosity", "inquiry", "new learning", "messages", "vigilance"],
                "reversed_keywords": ["cynicism", "misinformation", "scattered thinking", "mischief"],
                "guidance": "Curiosity leads to discovery. Ask questions and investigate. Knowledge empowers.",
            },
            "Knight of Swords": {
                "explanation": "The Knight of Swords represents swift action, directness, and intellectual courage. It embodies confrontation, truth-seeking, and the willingness to challenge.",
                "interpretation": "Direct communication and action, intellectual courage, challenging situations, swift movement",
                "keywords": ["action", "impulsiveness", "courage", "conflict", "truth"],
                "reversed_keywords": ["scatter-brained", "dishonest", "confusion", "retreat"],
                "guidance": "Speak your truth directly. Act with courage. Swift action brings results.",
            },
            "Queen of Swords": {
                "explanation": "The Queen of Swords represents intellectual power, clarity, and independent thinking. It embodies wisdom gained through experience and clear perception.",
                "interpretation": "Intellectual power and clarity, independence and perception, wisdom and experience, communication",
                "keywords": ["clarity", "intelligence", "independence", "truth", "perception"],
                "reversed_keywords": ["bitter", "manipulative", "cold", "cruel"],
                "guidance": "Trust your keen intellect. Speak your truth with grace. Clarity empowers.",
            },
            "King of Swords": {
                "explanation": "The King of Swords represents mental mastery, authority through intellect, and the power of truth. It embodies leadership, clear judgment, and strategic thinking.",
                "interpretation": "Mental mastery and intellect, authority and leadership, justice and fairness, clear judgment",
                "keywords": ["authority", "intellect", "truth", "leadership", "justice"],
                "reversed_keywords": ["tyrant", "manipulation", "abuse of power", "cruelty"],
                "guidance": "Lead with intellect and integrity. Your clarity creates order. Speak truth with authority.",
            },
            "Princess of Swords": {
                "explanation": "The Princess of Swords represents intellectual potential, youthful curiosity, and emerging clarity. It embodies the development of mental acuity and the pursuit of knowledge.",
                "interpretation": "Intellectual development and potential, emerging clarity, youthful inquiry, pursuit of truth",
                "keywords": ["clarity emerging", "intellectual potential", "investigation", "truth-seeking", "perception"],
                "reversed_keywords": ["confusion", "scattered thoughts", "deception", "lack of focus"],
                "guidance": "Your ability to perceive truth is developing. Stay curious and focused. Clarity is emerging.",
            },
            
            # Minor Arcana - Cups
            "Ace of Cups": {
                "explanation": "The Ace of Cups represents new emotional beginning, love, and spiritual awakening. It embodies the opening of the heart and new emotional connections.",
                "interpretation": "New emotional beginning, love and compassion, spiritual awakening, emotional clarity",
                "keywords": ["love", "new emotion", "compassion", "beginning", "spirituality"],
                "reversed_keywords": ["blocked emotion", "closed heart", "emotional confusion"],
                "guidance": "Your heart opens to new possibilities. Emotional connections deepen. Love flows.",
            },
            "Two of Cups": {
                "explanation": "The Two of Cups represents partnership, mutual respect, and emotional connection. It embodies balance, harmony, and the foundation of relationships.",
                "interpretation": "Partnership and connection, mutual respect and harmony, emotional balance, agreements",
                "keywords": ["partnership", "love", "connection", "harmony", "commitment"],
                "reversed_keywords": ["imbalance", "separation", "misalignment", "broken agreement"],
                "guidance": "Deep connection and harmony are possible. Mutual respect forms the foundation.",
            },
            "Three of Cups": {
                "explanation": "The Three of Cups represents celebration, friendship, and community. It embodies joy, shared experiences, and the warmth of connection.",
                "interpretation": "Celebration and community, friendship and joy, shared experiences, social harmony",
                "keywords": ["celebration", "community", "friendship", "joy", "creativity"],
                "reversed_keywords": ["isolation", "loneliness", "overindulgence", "discord"],
                "guidance": "Celebrate with friends. Community and connection bring joy. Share in the abundance.",
            },
            
            # Minor Arcana - Pentacles
            "Ace of Pentacles": {
                "explanation": "The Ace of Pentacles represents new prosperity, material opportunity, and earthly beginnings. It embodies abundance, security, and practical gifts.",
                "interpretation": "New material opportunity, abundance and prosperity, earthly beginnings, practical gifts",
                "keywords": ["abundance", "opportunity", "prosperity", "security", "gift"],
                "reversed_keywords": ["lost opportunity", "scarcity", "blocked prosperity"],
                "guidance": "Material opportunity arrives. Seize it. Abundance begins with gratitude.",
            },
            "Two of Pentacles": {
                "explanation": "The Two of Pentacles represents balance, flexibility, and managing resources. It embodies juggling priorities, adaptability, and resourcefulness.",
                "interpretation": "Balance and flexibility, managing resources, adaptability, juggling priorities",
                "keywords": ["balance", "flexibility", "adaptability", "resourcefulness", "management"],
                "reversed_keywords": ["imbalance", "mismanagement", "chaos", "loss"],
                "guidance": "Balance your priorities carefully. Flexibility allows you to manage what comes.",
            },
            
            # Minor Arcana - Wands
            "Ace of Wands": {
                "explanation": "The Ace of Wands represents new inspiration, creative spark, and passionate new beginning. It embodies potential, growth, and spiritual fire.",
                "interpretation": "New creative spark, inspiration and potential, passionate beginning, growth opportunity",
                "keywords": ["inspiration", "potential", "growth", "new beginning", "creativity"],
                "reversed_keywords": ["blocked inspiration", "delays", "lost potential"],
                "guidance": "Creative inspiration ignites. Channel this energy into action. Your passion becomes power.",
            },
            "Two of Wands": {
                "explanation": "The Two of Wands represents planning, future vision, and resourcefulness. It embodies potential growth, decisions about direction, and careful preparation.",
                "interpretation": "Planning and vision, resource management, decisions about direction, future planning",
                "keywords": ["vision", "planning", "potential", "resourcefulness", "future"],
                "reversed_keywords": ["lack of vision", "poor planning", "blocked growth"],
                "guidance": "Plan your future with vision. You have resources to build something great.",
            },
        }
    
    def get(self, card_name: str) -> Optional[Dict[str, Any]]:
        """
        Get details for a specific card by name.
        
        Args:
            card_name: The card's name (e.g., "Princess of Swords", "Ace of Cups")
            
        Returns:
            Dictionary containing card details, or None if not found
        """
        return self._details.get(card_name)
    
    def get_key_as_roman(self, card_name: str) -> Optional[str]:
        """
        Get the card's key displayed as Roman numerals.
        
        Args:
            card_name: The card's name (e.g., "The Fool", "The Magician")
            
        Returns:
            Roman numeral representation of the key (e.g., "XXI" for 21), or None if not found
        """
        details = self.get(card_name)
        if details and "key" in details:
            return self.key_to_roman(details["key"])
        return None
    
    def get_all_by_suit(self, suit_name: str) -> Dict[str, Dict[str, Any]]:
        """
        Get all details for cards in a specific suit.
        
        Args:
            suit_name: The suit name ("Cups", "Pentacles", "Swords", "Wands")
            
        Returns:
            Dictionary of card details for that suit
        """
        return {
            name: details for name, details in self._details.items()
            if suit_name.lower() in name.lower()
        }
    
    def _get_registry_key_for_card(self, card: 'Card') -> Optional[str]:
        """
        Get the registry key for a card based on deck position (1-78).
        
        Card position is independent of deck-specific names, allowing different
        deck variants to use the same registry entries.
        
        Args:
            card: The Card object to look up
            
        Returns:
            Registry key string, or None if card cannot be mapped
        """
        return self._position_map.get(card.number)
    
    def load_into_card(self, card: 'Card') -> bool:
        """
        Load details from registry into a Card object using its position.
        
        Args:
            card: The Card object to populate
            
        Returns:
            True if details were found and loaded, False otherwise
        """
        # Use position-based lookup instead of name-based
        details = self.get_by_position(card.number)
        if not details:
            return False
        
        card.explanation = details.get("explanation", "")
        card.interpretation = details.get("interpretation", "")
        card.keywords = details.get("keywords", [])
        card.reversed_keywords = details.get("reversed_keywords", [])
        card.guidance = details.get("guidance", "")
        
        return True
    
    def __getitem__(self, card_name: str) -> Optional[Dict[str, Any]]:
        """Allow dict-like access: registry['Princess of Swords']"""
        return self.get(card_name)
