from __future__ import annotations

import json

from app.core.agent.processes.v2.workflows.doc_update_from_feature.workflow_runtime.context import DocUpdateFromFeatureContext
from app.core.agent.utils.workflow import WorkflowStep


class FinalizeAnswerStep(WorkflowStep[DocUpdateFromFeatureContext]):
    step_id = "finalize"
    title = "Подготовка ответа"

    async def run(self, context: DocUpdateFromFeatureContext) -> DocUpdateFromFeatureContext:
        if context.answer:
            return context
        lines: list[str] = ["DOC_UPDATE/FROM_FEATURE: результат построения changeset."]
        if context.issues:
            lines.append("\nОбнаружены несоответствия/нехватка данных:")
            for issue in context.issues:
                lines.append(f"- {issue}")
        lines.append("\nПлан изменений:")
        if not context.planned_changes:
            lines.append("- Не сформирован.")
        else:
            for item in context.planned_changes:
                lines.append(f"- {item.op}: {item.path} ({item.doc_type})")
        lines.append("\nChangeset (для плагина):")
        lines.append("```json")
        lines.append(json.dumps([item.model_dump() for item in context.changeset], ensure_ascii=False, indent=2))
        lines.append("```")
        context.apply_changeset = bool(context.changeset)
        lines.append(f"\napply_changeset: {str(context.apply_changeset).lower()}")
        context.answer = "\n".join(lines)
        context.answer_generated_payload = {
            "answer_mode": "docs_update_changeset",
            "answer_length": len(context.answer),
            "changeset_items": len(context.changeset),
            "apply_changeset": context.apply_changeset,
        }
        return context

    def trace_output(self, context: DocUpdateFromFeatureContext) -> dict[str, object]:
        return {
            "answer_length": len(context.answer),
            "issues": len(context.issues),
            "changeset_items": len(context.changeset),
        }
