"""Verifier Agent — classifies vulnerabilities as True Positive or False Positive."""

from __future__ import annotations

import logging

from secagent.context.context_builder import extract_snippet
from secagent.llm.grok_client import GrokClient
from secagent.models import Vulnerability, VerificationStatus
from secagent.prompts import load as _load_prompt

logger = logging.getLogger(__name__)

_SYSTEM_PROMPT = _load_prompt("verifier.txt")


def verify_vulnerability(
    vuln: Vulnerability,
    client: GrokClient | None = None,
) -> VerificationStatus:
    """Classify *vuln* as TP or FP using LLM reasoning.

    Falls back to TP when no LLM client is available (conservative).
    """
    snippet = extract_snippet(vuln.file, vuln.line) if vuln.line > 0 else ""

    user_prompt = (
        f"Scanner: {vuln.scanner}\n"
        f"Type: {vuln.vuln_type}\n"
        f"File: {vuln.file}\n"
        f"Line: {vuln.line}\n"
        f"Description: {vuln.description}\n\n"
        f"Code snippet:\n```\n{snippet}\n```"
    )

    if client and client.api_key:
        result = client.chat(_SYSTEM_PROMPT, user_prompt)
        if isinstance(result, dict):
            status = result.get("status", "TP").upper()
            if status in ("TP", "FP"):
                logger.info("Verifier: %s → %s", vuln.id, status)
                return VerificationStatus(status)

    # Conservative fallback
    logger.info("Verifier fallback: marking %s as TP", vuln.id)
    return VerificationStatus.TP
