"""Custom promptfoo provider that runs NoiseGate triage on a report."""

import json
import sys
from pathlib import Path

# Ensure the project root is importable
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import yaml

from noisegate.llm import get_default_model
from noisegate.models import Check, Policy, Program, Report
from noisegate.program import load_program
from noisegate.triage import run_triage

PROGRAMS_DIR = Path(__file__).parent / "programs"


def _load_default_policy() -> Policy:
    policy_path = Path(__file__).resolve().parent.parent / "noisegate" / "data" / "default_policy.yaml"
    with open(policy_path) as f:
        raw = yaml.safe_load(f)
    return Policy(checks=[Check(**c) for c in raw["checks"]])


def call_api(prompt, options, context):
    """promptfoo provider entry point."""
    vars_ = context.get("vars", {})

    report_text = vars_.get("report_text", "")
    if not report_text:
        return {"output": "", "error": "No report_text in vars"}

    program_name = vars_.get("program_name", "")
    program_path = PROGRAMS_DIR / f"{program_name}.yaml"
    if not program_path.exists():
        return {"output": "", "error": f"No program definition for '{program_name}'"}

    program = load_program(program_path)

    report = Report(
        raw_text=report_text[:100_000],
        source_path=f"h1_report_{vars_.get('report_id', 'unknown')}",
        char_count=min(len(report_text), 100_000),
    )

    policy = _load_default_policy()
    model = get_default_model()

    try:
        result = run_triage(policy.checks, report, program, model=model)
        output = json.dumps(result.model_dump(), indent=2)
        return {
            "output": output,
            "tokenUsage": {
                "prompt": result.prompt_tokens,
                "completion": result.completion_tokens,
                "total": result.prompt_tokens + result.completion_tokens,
            },
        }
    except Exception as e:
        return {"output": "", "error": str(e)}
