"""Validator Agent — confirms that a proposed fix is correct and safe."""

from __future__ import annotations

import logging

from secagent.llm.grok_client import GrokClient
from secagent.models import FixResult, ValidationResult
from secagent.prompts import load as _load_prompt

logger = logging.getLogger(__name__)

_SYSTEM_PROMPT = _load_prompt("validator.txt")


def validate_fix(
    fix: FixResult,
    client: GrokClient | None = None,
) -> ValidationResult:
    """Ask the LLM to validate *fix* before it is applied.

    Returns a ``ValidationResult``; defaults to valid when no LLM is
    available (so the pipeline can proceed in offline mode).
    """
    user_prompt = (
        f"Vulnerability: {fix.vulnerability.description}\n"
        f"File: {fix.file}\n\n"
        f"Original code:\n```\n{fix.original_snippet}\n```\n\n"
        f"Patched code:\n```\n{fix.patched_snippet}\n```"
    )

    if client and client.api_key:
        result = client.chat(_SYSTEM_PROMPT, user_prompt)
        if isinstance(result, dict):
            valid = result.get("valid", False)
            reason = result.get("reason", "")
            logger.info(
                "Validator: %s → %s (%s)",
                fix.vulnerability.id,
                "VALID" if valid else "INVALID",
                reason,
            )
            return ValidationResult(valid=bool(valid), reason=reason, fix=fix)

    # Fallback: assume valid (allow pipeline to continue)
    logger.info("Validator fallback: treating fix for %s as valid.", fix.vulnerability.id)
    return ValidationResult(valid=True, reason="No LLM validation available.", fix=fix)
