#!/usr/bin/env python3
import sys
sys.path.insert(0, '.')

from tarot_oracle.tarot import MAJOR_ARCANA, MINOR_ARCANA
from tarot_oracle.data_loader import BundledDataLoader


def validate_major_arcana(deck: dict) -> int:
    cards = deck.get('cards', [])
    major_cards = [c for c in cards if c.get('card_type') == 'major']
    failures = []

    for card in major_cards:
        name = card.get('name', '')
        lookup_key = name.replace('The ', '') if name.startswith('The ') else name

        if lookup_key not in MAJOR_ARCANA:
            failures.append(f"Major Arcana: '{name}' - Key '{lookup_key}' not found in MAJOR_ARCANA")
            continue

        expected_keywords = MAJOR_ARCANA[lookup_key]
        actual_keywords = card.get('keywords', '')

        if expected_keywords.lower() != actual_keywords.lower():
            failures.append(
                f"Major Arcana: '{name}' - Keywords mismatch\n"
                f"  Expected: {expected_keywords}\n"
                f"  Actual:   {actual_keywords}"
            )

    return failures


def validate_minor_arcana(deck: dict) -> list[str]:
    cards = deck.get('cards', [])
    minor_cards = [c for c in cards if c.get('card_type') == 'minor']
    failures = []

    for card in minor_cards:
        suit = card.get('suit', '')
        value = card.get('value', '')
        lookup_key = f"{suit}_{value}"

        if lookup_key not in MINOR_ARCANA:
            failures.append(f"Minor Arcana: '{card.get('name')}' - Key '{lookup_key}' not found in MINOR_ARCANA")
            continue

        expected_keywords = MINOR_ARCANA[lookup_key]
        actual_keywords = card.get('keywords', '')

        if expected_keywords.lower() != actual_keywords.lower():
            failures.append(
                f"Minor Arcana: '{card.get('name')}' - Keywords mismatch\n"
                f"  Expected: {expected_keywords}\n"
                f"  Actual:   {actual_keywords}"
            )

    return failures


def main():
    deck = BundledDataLoader.load_deck('rider-waite')

    if not deck:
        print("Error: Could not load rider-waite deck")
        return 1

    major_failures = validate_major_arcana(deck)
    minor_failures = validate_minor_arcana(deck)

    all_failures = major_failures + minor_failures

    if all_failures:
        print("Validation Failures:")
        print("-" * 60)
        for failure in all_failures:
            print(failure)
            print()

    cards = deck.get('cards', [])
    major_cards = [c for c in cards if c.get('card_type') == 'major']
    minor_cards = [c for c in cards if c.get('card_type') == 'minor']

    major_passed = len(major_cards) - len(major_failures)
    minor_passed = len(minor_cards) - len(minor_failures)

    print("-" * 60)
    print(f"Major Arcana: {major_passed}/{len(major_cards)} cards passed")
    print(f"Minor Arcana: {minor_passed}/{len(minor_cards)} cards passed")

    return 1 if all_failures else 0


if __name__ == '__main__':
    sys.exit(main())
