"""Quick test script for Phase 2 taxonomy loader."""

import sys
from pathlib import Path

# Add project root to path
sys.path.insert(0, str(Path(__file__).parent))

from src.extraction_v2.taxonomy_loader import TaxonomyLoader


def test_standard_taxonomy():
    """Test loading standard taxonomy."""
    print("=" * 60)
    print("TEST 1: Loading Standard Taxonomy (No Profile)")
    print("=" * 60)

    loader = TaxonomyLoader()

    print(f"\nVersion: {loader.taxonomy.get('version')}")
    print(f"Description: {loader.taxonomy.get('description')}")

    # Count tags per namespace
    namespaces = loader.taxonomy.get("namespaces", {})
    print(f"\nNamespaces ({len(namespaces)}):")
    for ns_name, ns_data in namespaces.items():
        tag_count = len(ns_data.get("tags", []))
        desc = ns_data.get("description", "")
        print(f"  - {ns_name}: {tag_count} tags - {desc}")

    # Show dynamic namespaces
    dynamic = loader.get_dynamic_namespaces()
    print(f"\nDynamic Namespaces ({len(dynamic)}): {', '.join(dynamic)}")

    # Test tag validation
    print("\n" + "=" * 60)
    print("Tag Validation Tests")
    print("=" * 60)

    test_tags = [
        "req:functional",  # Valid pre-defined
        "topic:authentication",  # Valid dynamic
        "entity:aws_s3",  # Valid dynamic
        "misc:something",  # Forbidden namespace
        "security",  # Missing namespace
        "req:nonexistent",  # Invalid tag name
    ]

    for tag in test_tags:
        is_valid, reason = loader.is_valid_tag(tag)
        status = "✓ VALID" if is_valid else "✗ INVALID"
        print(f"  {status}: {tag:30s} {f'({reason})' if reason else ''}")

    print("\nAll Pre-defined Tags Count:", len(loader.get_all_tags()))
    print()


def test_fintech_profile():
    """Test loading fintech profile."""
    print("=" * 60)
    print("TEST 2: Loading Fintech Profile")
    print("=" * 60)

    loader = TaxonomyLoader(profile="fintech")

    print(f"\nVersion: {loader.taxonomy.get('version')}")
    print(f"Profile: {loader.profile_name}")

    # Check for fintech-specific tags
    namespaces = loader.taxonomy.get("namespaces", {})
    print(f"\nNamespaces ({len(namespaces)}):")
    for ns_name in sorted(namespaces.keys()):
        ns_data = namespaces[ns_name]
        tag_count = len(ns_data.get("tags", []))
        print(f"  - {ns_name}: {tag_count} tags")

    # Check for fintech-specific tags
    compliance_tags = loader.get_namespace_info("compliance")
    if compliance_tags:
        print("\nFintech Compliance Tags:")
        for tag in compliance_tags.get("tags", []):
            print(f"  - compliance:{tag['name']} - {tag['description']}")

    print("\nTotal Pre-defined Tags:", len(loader.get_all_tags()))
    print()


def test_healthcare_profile():
    """Test loading healthcare profile."""
    print("=" * 60)
    print("TEST 3: Loading Healthcare Profile")
    print("=" * 60)

    loader = TaxonomyLoader(profile="healthcare")

    print(f"\nVersion: {loader.taxonomy.get('version')}")
    print(f"Profile: {loader.profile_name}")

    # Check for class namespace (healthcare-specific)
    class_ns = loader.get_namespace_info("class")
    if class_ns:
        print("\nMedical Device Classifications:")
        for tag in class_ns.get("tags", []):
            print(f"  - class:{tag['name']} - {tag['description']}")

    print("\nTotal Pre-defined Tags:", len(loader.get_all_tags()))
    print()


def test_automotive_profile():
    """Test loading automotive profile."""
    print("=" * 60)
    print("TEST 4: Loading Automotive Profile")
    print("=" * 60)

    loader = TaxonomyLoader(profile="automotive")

    print(f"\nVersion: {loader.taxonomy.get('version')}")
    print(f"Profile: {loader.profile_name}")

    # Check for ASIL risk tags
    risk_ns = loader.get_namespace_info("risk")
    if risk_ns:
        asil_tags = [t for t in risk_ns.get("tags", []) if "asil" in t["name"]]
        if asil_tags:
            print("\nASIL Safety Levels:")
            for tag in asil_tags:
                print(f"  - risk:{tag['name']} - {tag['description']}")

    # Check hw namespace (automotive-specific)
    hw_ns = loader.get_namespace_info("hw")
    if hw_ns:
        print("\nHardware Interface Tags:")
        for tag in hw_ns.get("tags", []):
            print(f"  - hw:{tag['name']} - {tag['description']}")

    print("\nTotal Pre-defined Tags:", len(loader.get_all_tags()))
    print()


if __name__ == "__main__":
    try:
        test_standard_taxonomy()
        test_fintech_profile()
        test_healthcare_profile()
        test_automotive_profile()

        print("=" * 60)
        print("ALL TESTS PASSED ✓")
        print("=" * 60)

    except Exception as e:
        print(f"\n✗ ERROR: {e}")
        import traceback

        traceback.print_exc()
        sys.exit(1)
