"""Test script for Phase 3 tagging with inheritance and confidence."""

import sys
from pathlib import Path

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

from src.extraction_v2.inheritance_engine import InheritanceEngine
from src.extraction_v2.tag_validator import TagValidator
from src.extraction_v2.taxonomy_loader import TaxonomyLoader


def test_tag_validator():
    """Test tag validation."""
    print("=" * 60)
    print("TEST 1: Tag Validator")
    print("=" * 60)

    loader = TaxonomyLoader()
    validator = TagValidator(loader)

    test_cases = [
        ("req:functional", "Valid pre-defined tag"),
        ("topic:authentication", "Valid dynamic tag"),
        ("entity:AWS", "Valid entity (allows uppercase)"),
        ("topic:認証", "Invalid - non-ASCII in topic"),
        ("misc:test", "Invalid - forbidden namespace"),
        ("security", "Invalid - missing namespace"),
        ("req:quality:security", "Valid nested tag"),
        ("unknown:test", "Flagged - unknown namespace (discovery mode)"),
    ]

    for tag, description in test_cases:
        is_valid, status, reason = validator.validate_tag(tag)
        result = "✓" if is_valid else "✗"
        print(f"\n{result} {tag}")
        print(f"   Description: {description}")
        print(f"   Status: {status}")
        if reason:
            print(f"   Reason: {reason}")

    print("\n")


def test_inheritance_engine():
    """Test tag inheritance."""
    print("=" * 60)
    print("TEST 2: Inheritance Engine")
    print("=" * 60)

    engine = InheritanceEngine()

    # Test document-level tags
    print("\nDocument-level tags:")
    doc_tags = engine.extract_document_tags(
        filename="requirements_specification.xlsx",
        metadata={"project": "Authentication Service", "domain": "fintech"},
    )
    for tag in doc_tags:
        print(
            f"  - {tag.name} (source={tag.source.value}, confidence={tag.confidence})"
        )

    # Test section-level tags
    print("\nSection-level tags:")
    section_tags = engine.extract_section_tags(
        parent_header="3. Security Requirements", sheet_name="Authentication"
    )
    for tag in section_tags:
        print(
            f"  - {tag.name} (source={tag.source.value}, confidence={tag.confidence})"
        )

    # Test merging
    print("\nMerging tags:")
    from src.api.schemas.tags import TagAssignment, TagHistoryEntry, TagSource, TagStatus
    from uuid import uuid4
    import time

    block_tags = [
        TagAssignment(
            tag_id=str(uuid4()),
            name="req:quality:security",
            source=TagSource.AI,
            confidence=0.95,
            status=TagStatus.VERIFIED,
            history=[
                TagHistoryEntry(action="suggested", by="ai", ts=int(time.time()))
            ],
        )
    ]

    merged = engine.merge_tags(doc_tags, section_tags, block_tags)
    print(f"\n  Total tags after merge: {len(merged)}")
    for tag in merged:
        print(
            f"    - {tag.name} (source={tag.source.value}, confidence={tag.confidence})"
        )

    print("\n")


def test_confidence_based_status():
    """Test confidence-based status determination."""
    print("=" * 60)
    print("TEST 3: Confidence-Based Status")
    print("=" * 60)

    from src.extraction_v2.semantic_tagger import SemanticTagger

    tagger = SemanticTagger()

    test_cases = [
        ("req:functional", 0.95, "Should be VERIFIED (predefined + high confidence)"),
        ("req:functional", 0.75, "Should be PENDING (predefined + moderate)"),
        ("topic:authentication", 0.95, "Should be PENDING (dynamic tag)"),
        ("topic:authentication", 0.55, "Should be REJECTED (too low)"),
    ]

    for tag_name, confidence, expected in test_cases:
        status = tagger._determine_tag_status(confidence, "valid", tag_name)
        print(f"\nTag: {tag_name}")
        print(f"Confidence: {confidence}")
        print(f"Status: {status.value}")
        print(f"Expected: {expected}")

    print("\n")


def test_full_pipeline():
    """Test full tagging pipeline with mock LLM response."""
    print("=" * 60)
    print("TEST 4: Full Pipeline (Mock LLM)")
    print("=" * 60)

    from src.extraction_v2.semantic_tagger import SemanticTagger

    tagger = SemanticTagger(profile="fintech")

    # Simulate LLM response format
    mock_llm_tags = [
        {"name": "req:functional", "confidence": 1.0},
        {"name": "req:quality:security", "confidence": 0.95},
        {"name": "compliance:pci_dss", "confidence": 0.90},
        {"name": "topic:payment_gateway", "confidence": 0.85},
        {"name": "entity:stripe", "confidence": 0.80},
        {"name": "misc:invalid", "confidence": 0.90},  # Should be rejected
    ]

    print("\nProcessing mock LLM tags...")
    tag_assignments = tagger._process_llm_tags(mock_llm_tags)

    print(f"\nProcessed {len(tag_assignments)} valid tags:")
    for tag in tag_assignments:
        print(
            f"  - {tag.name} (confidence={tag.confidence}, status={tag.status.value})"
        )

    # Check auto-approval
    verified_count = sum(1 for t in tag_assignments if t.status.value == "verified")
    pending_count = sum(1 for t in tag_assignments if t.status.value == "pending")

    print(f"\nAuto-approved (verified): {verified_count}")
    print(f"Needs review (pending): {pending_count}")

    print("\n")


def test_record_tagging():
    """Test tagging full records with inheritance."""
    print("=" * 60)
    print("TEST 5: Full Record Tagging")
    print("=" * 60)

    from src.extraction_v2.semantic_tagger import SemanticTagger

    tagger = SemanticTagger(profile="fintech")

    # Mock records
    records = [
        {
            "id": 1,
            "text": "The system shall validate JWT tokens for all API requests.",
            "parent_header": "3.1 Authentication Requirements",
            "sheet_name": "Security",
        },
        {
            "id": 2,
            "text": "Payment data must be encrypted using AES-256.",
            "parent_header": "3.2 Data Protection",
            "sheet_name": "Security",
        },
    ]

    # Simulate LLM tagging (we'd need to mock the LLM call for real test)
    print("\nMock tagging scenario:")
    print(f"  Filename: payment_system_requirements.xlsx")
    print(f"  Metadata: {{'project': 'Payment Gateway', 'domain': 'fintech'}}")
    print(f"  Records: {len(records)}")

    # Manually apply some tags for demonstration
    from src.api.schemas.tags import TagAssignment, TagHistoryEntry, TagSource, TagStatus
    from uuid import uuid4
    import time

    records[0]["tags"] = [
        TagAssignment(
            tag_id=str(uuid4()),
            name="req:functional",
            source=TagSource.AI,
            confidence=1.0,
            status=TagStatus.VERIFIED,
            history=[
                TagHistoryEntry(action="suggested", by="ai", ts=int(time.time()))
            ],
        )
    ]

    records[1]["tags"] = [
        TagAssignment(
            tag_id=str(uuid4()),
            name="compliance:pci_dss",
            source=TagSource.AI,
            confidence=0.95,
            status=TagStatus.VERIFIED,
            history=[
                TagHistoryEntry(action="suggested", by="ai", ts=int(time.time()))
            ],
        )
    ]

    # Apply inheritance
    result = tagger.inheritance_engine.apply_inheritance(
        records,
        filename="payment_system_requirements.xlsx",
        metadata={"project": "Payment Gateway", "domain": "fintech"},
    )

    print("\nAfter inheritance:")
    for record in result:
        print(f"\nRecord {record['id']}: {record['text'][:50]}...")
        print(f"  Tags ({len(record['tags'])}):")
        for tag in record["tags"]:
            print(
                f"    - {tag.name} (source={tag.source.value}, confidence={tag.confidence}, status={tag.status.value})"
            )

    print("\n")


if __name__ == "__main__":
    try:
        test_tag_validator()
        test_inheritance_engine()
        test_confidence_based_status()
        test_full_pipeline()
        test_record_tagging()

        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)
