"""MVP test: run the extraction loop on 01-practice.pdf.

This is the simplest end-to-end test — hardcoded gold, one page, simple schema.
Run with: cd /Users/soma/Development/natural-pdf && .venv/bin/python agentic/test_mvp.py
"""

import json
import sys
from pathlib import Path

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

from agentic.config import AgentConfig
from agentic.models import FieldSchema
from agentic.session import ExtractionRunner

# ── Schema ───────────────────────────────────────────────────────────────────

schema = [
    FieldSchema(name="site_name", description="Name of the inspection site"),
    FieldSchema(name="city", description="City of the inspection site"),
    FieldSchema(name="state", description="State of the inspection site"),
    FieldSchema(name="inspection_date", description="Date of inspection", field_type="date"),
    FieldSchema(name="violation_count", description="Number of violations", field_type="number"),
    FieldSchema(name="summary", description="Summary text"),
    FieldSchema(name="violations", description="Table of violations with columns: Statute, Description, Level, Repeat", field_type="list"),
]

# ── Gold (hardcoded for 01-practice.pdf) ─────────────────────────────────────

# Gold must match what's actually on the page
gold = {
    "site_name": "Durham\u2019s Meatpacking",
    "city": "Chicago",
    "state": "Ill.",
    "inspection_date": "February 3, 1905",
    "violation_count": "7",
    "summary": "Worst of any, however, were the fertilizer men, and those who served in the cooking rooms. These people could not be shown to the visitor - for the odor of a fertilizer man would scare any ordinary visitor at a hundred yards, and as for the other men, who worked in tank rooms full of steam, and in some of which there were open vats near the level of the floor, their peculiar trouble was that they fell into the vats; and when they were fished out, there was never enough of them left to be worth exhibiting - sometimes they would be overlooked for days, till all but the bones of them had gone out to the world as Durham\u2019s Pure Leaf Lard!",
    "violations": [
        {"statute": "4.12.7", "description": "Unsanitary Working Conditions.", "level": "Critical", "repeat": True},
        {"statute": "5.8.3", "description": "Inadequate Protective Equipment.", "level": "Serious", "repeat": True},
        {"statute": "6.3.9", "description": "Ineffective Injury Prevention.", "level": "Serious", "repeat": False},
        {"statute": "7.1.5", "description": "Failure to Properly Store Hazardous Materials.", "level": "Critical", "repeat": False},
        {"statute": "8.9.2", "description": "Lack of Adequate Fire Safety Measures.", "level": "Serious", "repeat": False},
        {"statute": "9.6.4", "description": "Inadequate Ventilation Systems.", "level": "Serious", "repeat": True},
        {"statute": "10.2.7", "description": "Insufficient Employee Training for Safe Work Practices.", "level": "Serious", "repeat": False},
    ],
}

# ── Config ───────────────────────────────────────────────────────────────────

config = AgentConfig(
    model="claude-sonnet-4-6",
    max_iterations=8,
    max_tokens=16384,
    target_score=1.0,
    python_command=str(Path(__file__).parent / ".venv" / "bin" / "python"),
    output_dir=str(Path(__file__).parent / "output"),
)

# ── Run ──────────────────────────────────────────────────────────────────────

def main():
    pdf_path = str(Path(__file__).parent.parent / "pdfs" / "01-practice.pdf")

    print(f"PDF: {pdf_path}")
    print(f"Schema: {[f.name for f in schema]}")
    print(f"Gold: {gold}")
    print(f"Model: {config.model}")
    print(f"Max iterations: {config.max_iterations}")
    print()

    runner = ExtractionRunner(config)
    session = runner.run(
        pdf_path=pdf_path,
        page_number=0,
        schema=schema,
        gold=gold,
    )

    # Print results
    print(f"\n{'='*60}")
    print(f"Session complete: {session.stop_reason}")
    print(f"Best score: {session.best_score:.0%}")
    print(f"Iterations: {len(session.attempts)}")
    print(f"Total tokens: {session.total_tokens}")
    print(f"Total time: {session.total_time_ms}ms")
    print()

    for attempt in session.attempts:
        print(f"--- Attempt {attempt.iteration + 1} ---")
        print(f"Score: {attempt.overall_score:.0%}")
        print(f"Approach: {attempt.diagnostics.approach_used}")
        if attempt.execution.error_type:
            print(f"Error: {attempt.execution.error_type} — {attempt.execution.error_message}")
        for comp in attempt.field_comparisons:
            status = "✓" if comp.match else "✗"
            print(f"  {status} {comp.field_name}: {comp.raw_actual} (expected: {comp.raw_expected})")
        if attempt.diagnostics.lessons:
            print("  Lessons:")
            for lesson in attempt.diagnostics.lessons:
                print(f"    - {lesson}")
        print()

    if session.best_script:
        print(f"\n{'='*60}")
        print("BEST SCRIPT:")
        print(session.best_script)

    # Save session
    output_path = Path(config.output_dir) / "test_session.json"
    session.to_json(output_path)
    print(f"\nSession saved to {output_path}")


if __name__ == "__main__":
    main()
