"""Summary-only drawing-set completeness agent."""

import json
from typing import Dict, List

from backend import config
from backend.agents.base import AgentResult, AgentScope, AgentUsage, failure
from backend.agents.prompts import COMPLETENESS_SYSTEM_PROMPT, COMPLETENESS_USER_PROMPT
from backend.llm import call_json
from backend.pipeline._stage import collect_list, validate_issue


def build_sheet_summaries(sheets: List[Dict]) -> List[Dict]:
    """Return counts and classifications only; never raw assertions."""
    return [{
        "sheet_number": sheet.get("sheet_number"),
        "sheet_title": sheet.get("sheet_title"),
        "discipline": sheet.get("discipline"),
        "drawing_type": sheet.get("drawing_type"),
        "level": sheet.get("level"),
        "assertion_count": len(sheet.get("assertions") or []),
        "unresolved_count": len(sheet.get("unresolved_items") or []),
    } for sheet in sheets]


class CompletenessAgent:
    name = "completeness"

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

    def run(self, scope: AgentScope) -> AgentResult:
        try:
            instruction = COMPLETENESS_USER_PROMPT
            for key in ("sheet_index", "sheet_summaries", "cluster_summary"):
                instruction = instruction.replace(
                    "{" + key + "}",
                    json.dumps(scope.payload.get(key) or {}, ensure_ascii=True),
                )
            parsed = call_json(
                system_prompt=COMPLETENESS_SYSTEM_PROMPT,
                user_text=instruction,
                max_tokens=config.QAQC_MAX_TOKENS,
                model=config.AGENT_COMPLETENESS_MODEL,
                usage_tracker=self.usage,
                usage_stage="agent.completeness",
            )
            findings = collect_list(
                parsed, "issues", lambda item: validate_issue(item, "qaqc")
            )
            for finding in findings:
                finding.update(agent=self.name, scope_id=scope.scope_id)
            return AgentResult(scope_id=scope.scope_id, artifacts=findings)
        except Exception as exc:
            return failure(scope, exc)
