from __future__ import annotations

import json
from typing import Any

from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.workflow_runtime.context import (
    DocUpdateFromFeatureV2Context,
)
from app.core.agent.utils.workflow import WorkflowStep


class FinalizeAnswerStep(WorkflowStep[DocUpdateFromFeatureV2Context]):
    step_id = "step7_finalize"
    title = "Формирование итогового ответа"

    async def run(self, context: DocUpdateFromFeatureV2Context) -> DocUpdateFromFeatureV2Context:
        if context.answer:
            return context
        lines: list[str] = ["DOC_UPDATE/FROM_FEATURE v2: сформирован changeset."]
        if context.issues:
            lines.append("\nIssues:")
            for issue in context.issues:
                lines.append(f"- {issue}")
        lines.append("\nTasks:")
        for task in context.requirement_tasks:
            lines.append(
                f"- {task.section_key or f'#{task.index + 1}'} {task.action.value}: {task.path}"
                f" [{task.platform or '-'} | {task.doc_type or '-'}]"
            )
        if not context.requirement_tasks:
            lines.append("- Нет задач для обработки.")
        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_v2",
            "changeset_items": len(context.changeset),
            "apply_changeset": context.apply_changeset,
        }
        return context

    def trace_input(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        return {
            "tasks_count": len(context.requirement_tasks),
            "changeset_count": len(context.changeset),
            "issues_count": len(context.issues),
        }

    def trace_output(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        return {
            "answer_generated_payload": dict(context.answer_generated_payload or {}),
            "answer_len": len(context.answer or ""),
            "apply_changeset": context.apply_changeset,
        }
