"""Integration tests that call real LLM APIs.

These tests are skipped by default. Run with:
    pytest -m integration tests/test_integration.py -v

Requires ANTHROPIC_API_KEY environment variable.
"""
import os
import pytest
from pathlib import Path

# Skip all tests in this module if no API key
pytestmark = pytest.mark.skipif(
    not os.getenv("ANTHROPIC_API_KEY"),
    reason="ANTHROPIC_API_KEY not set"
)


@pytest.fixture
def xlsx_skill_dir():
    """Path to the real xlsx skill from skills/office/public/xlsx/."""
    skill_path = Path(__file__).parent.parent / "skills" / "office" / "public" / "xlsx"
    if not skill_path.exists():
        pytest.skip(f"xlsx skill not found at {skill_path}")
    return skill_path


@pytest.mark.integration
def test_real_extraction_xlsx(xlsx_skill_dir, tmp_path):
    """Test real LLM extraction on xlsx skill.

    This test actually calls the Anthropic API to extract skill metadata.
    It validates the entire extraction pipeline end-to-end.
    """
    from extractor import generate_skill_id, compute_skill_hash
    from transformer import tool_use_loop

    skill_id = generate_skill_id(xlsx_skill_dir.name)
    skill_hash = compute_skill_hash(xlsx_skill_dir)

    print(f"\nExtracting skill: {skill_id}")
    print(f"  Path: {xlsx_skill_dir}")
    print(f"  Hash: {skill_hash[:16]}...")

    result = tool_use_loop(xlsx_skill_dir, skill_hash, skill_id)

    # Verify extraction results
    assert result is not None, "Extraction returned None"
    assert result.id == skill_id, f"Skill ID mismatch: {result.id} != {skill_id}"
    assert result.hash == skill_hash, f"Hash mismatch"
    assert result.nature, "Nature should not be empty"
    assert len(result.intents) >= 1, f"Expected at least 1 intent, got {len(result.intents)}"
    assert result.generated_by, "generated_by should be set"
    assert result.generated_by != "unknown", "generated_by should not be 'unknown'"

    print(f"\nExtraction results:")
    print(f"  Nature: {result.nature[:100]}...")
    print(f"  Genus: {result.genus}")
    print(f"  Intents: {result.intents}")
    print(f"  Generated by: {result.generated_by}")

    if result.state_transitions.requires_state:
        print(f"  Requires state: {result.state_transitions.requires_state}")
    if result.state_transitions.yields_state:
        print(f"  Yields state: {result.state_transitions.yields_state}")


@pytest.mark.integration
def test_real_compile_xlsx(xlsx_skill_dir, tmp_path):
    """Test full compile pipeline on xlsx skill.

    This tests: extraction -> serialization -> module creation -> index generation
    """
    from extractor import generate_skill_id, compute_skill_hash
    from transformer import tool_use_loop
    from loader import create_core_ontology, serialize_skill_to_module, generate_index_manifest

    # Setup output directory
    output_dir = tmp_path / "ontoskills"
    output_dir.mkdir(parents=True)

    # Create core ontology
    core_path = output_dir / "ontoskills-core.ttl"
    print(f"\nCreating core ontology at {core_path}")
    create_core_ontology(core_path)
    assert core_path.exists(), "Core ontology should be created"

    # Extract skill
    skill_id = generate_skill_id(xlsx_skill_dir.name)
    skill_hash = compute_skill_hash(xlsx_skill_dir)
    print(f"Extracting skill: {skill_id}")
    skill = tool_use_loop(xlsx_skill_dir, skill_hash, skill_id)

    assert skill is not None, "Skill extraction failed"

    # Serialize to module (mirrors path structure)
    skill_output_path = output_dir / "office" / "public" / "xlsx" / "ontoskill.ttl"
    print(f"Serializing to {skill_output_path}")
    serialize_skill_to_module(skill, skill_output_path)
    assert skill_output_path.exists(), "Skill module should be created"

    # Generate index
    index_path = output_dir / "index.ttl"
    print(f"Generating index at {index_path}")
    generate_index_manifest([skill_output_path], index_path, output_dir)
    assert index_path.exists(), "Index manifest should be created"

    # Verify module can be loaded
    from loader import load_skill_module
    graph = load_skill_module(skill_output_path)
    assert len(graph) > 0, "Module should contain triples"

    print(f"\nCompile results:")
    print(f"  Module path: {skill_output_path}")
    print(f"  Triples in module: {len(graph)}")
    print(f"  Core path: {core_path}")
    print(f"  Index path: {index_path}")


@pytest.mark.integration
def test_real_security_check():
    """Test real LLM security review.

    This tests the LLM-as-judge security review with actual API calls.
    """
    from security import llm_security_review, check_patterns

    # Test safe content - first check patterns (no threats), then LLM
    safe_content = "This is a normal document about cooking pasta."
    threats = check_patterns(safe_content)
    result = llm_security_review(safe_content, threats)
    assert result.safe, "Safe content should pass"
    print(f"\nSafe content check: {result.safe}")

    # Test suspicious-looking but benign content
    educational = "The user wants to understand how prompt injection works for educational purposes."
    threats = check_patterns(educational)
    result = llm_security_review(educational, threats)
    print(f"Educational content check: {result.safe}, reason: {result.reason}")
