"""One-finding-per-call RFI writers."""

from backend import config
from backend.agents.base import AgentResult, AgentScope, AgentUsage, failure
from backend.llm import call_json
from backend.pipeline._serialize import dumps
from backend.pipeline.rfi import _valid_rfi
from backend.prompts import RFI_SYSTEM_PROMPT, RFI_USER_INSTRUCTION


class RFIWriterAgent:
    name = "rfi_writer"

    def __init__(self, usage: AgentUsage) -> None:
        self.usage = usage

    def run(self, scope: AgentScope) -> AgentResult:
        try:
            finding = scope.payload["finding"]
            instruction = RFI_USER_INSTRUCTION.replace(
                "{prioritized_issues}", dumps([finding])
            )
            parsed = call_json(
                system_prompt=RFI_SYSTEM_PROMPT,
                user_text=instruction,
                max_tokens=config.RFI_MAX_TOKENS,
                model=config.AGENT_RFI_MODEL,
                usage_tracker=self.usage,
                usage_stage="agent.rfi",
            )
            candidates = parsed if isinstance(parsed, list) else (
                parsed.get("rfi_comments") if isinstance(parsed, dict) else []
            )
            rfis = []
            for candidate in candidates or []:
                rfi = _valid_rfi(candidate)
                if rfi:
                    rfi["issue_id"] = rfi.get("issue_id") or finding.get("issue_id")
                    rfis.append(rfi)
            return AgentResult(scope_id=scope.scope_id, artifacts=rfis[:1])
        except Exception as exc:
            return failure(scope, exc)
