"""Workflow Checkpointer — 工作流状态持久化与恢复。

将 WorkflowPlan + ExecutionContext 序列化为 JSON 文件,
支持中断后恢复执行。
"""

from __future__ import annotations

import json
import os
import time
from dataclasses import fields
from datetime import datetime
from pathlib import Path
from typing import Any

from app.config import settings
from app.tools.workflow.types import (
    ExecutionContext,
    StepStatus,
    StepType,
    WorkflowPlan,
    WorkflowStep,
)


def _get_checkpoint_dir() -> Path:
    """获取 checkpoint 存储目录。"""
    custom = getattr(settings, "workflow_checkpoint_dir", None)
    if custom:
        path = Path(custom)
    else:
        path = Path.home() / ".mofix" / "workflows"
    path.mkdir(parents=True, exist_ok=True)
    return path


class Checkpointer:
    """工作流状态持久化。"""

    def __init__(self, checkpoint_dir: str | Path | None = None):
        self._dir = Path(checkpoint_dir) if checkpoint_dir else _get_checkpoint_dir()

    async def save(self, plan: WorkflowPlan, ctx: ExecutionContext) -> None:
        """保存工作流状态到 JSON 文件。"""
        data = {
            "workflow_id": plan.workflow_id,
            "saved_at": time.time(),
            "saved_at_iso": datetime.now().isoformat(),
            "plan": self._plan_to_dict(plan),
            "context": self._context_to_dict(ctx),
        }

        filepath = self._dir / f"{plan.workflow_id}.json"
        # 原子写:先写临时文件再 rename
        tmp_path = filepath.with_suffix(".tmp")
        tmp_path.write_text(
            json.dumps(data, ensure_ascii=False, indent=2, default=str),
            encoding="utf-8",
        )
        # os.replace 跨平台原子覆盖;Path.rename 在 Windows 目标已存在时抛 FileExistsError
        os.replace(tmp_path, filepath)

    async def load(self, workflow_id: str) -> tuple[WorkflowPlan, ExecutionContext] | None:
        """从 JSON 文件恢复工作流状态。"""
        filepath = self._dir / f"{workflow_id}.json"
        if not filepath.is_file():
            return None

        try:
            data = json.loads(filepath.read_text(encoding="utf-8", errors="ignore"))
            if not isinstance(data, dict) or data.get("workflow_id") != workflow_id:
                return None
            plan_dict = data.get("plan", {})
            ctx_dict = data.get("context", {})
            if not isinstance(plan_dict, dict) or not isinstance(ctx_dict, dict):
                return None
            steps = plan_dict.get("steps", [])
            metadata = plan_dict.get("metadata", {})
            if not isinstance(steps, list) or not isinstance(metadata, dict):
                return None
            if any(
                not isinstance(ctx_dict.get(key, {}), dict)
                for key in ("variables", "step_results", "errors", "metadata")
            ):
                return None

            plan = WorkflowPlan(
                workflow_id=workflow_id,
                intent=plan_dict.get("intent", ""),
                goal=plan_dict.get("goal", ""),
                steps=[self._step_from_dict(step) for step in steps],
                max_concurrency=self._coerce_positive_int(plan_dict.get("max_concurrency", 3)),
                verify_enabled=plan_dict.get("verify_enabled", True),
                metadata=metadata,
            )
            if plan.max_concurrency is None:
                return None
            ctx = ExecutionContext(
                workflow_id=workflow_id,
                variables=ctx_dict.get("variables", {}),
                step_results=ctx_dict.get("step_results", {}),
                errors=ctx_dict.get("errors", {}),
                metadata=ctx_dict.get("metadata", {}),
            )
        except (ValueError, TypeError, KeyError, RecursionError, OSError):
            # 合法 JSON 也可能有损坏的层级或枚举值;不得让恢复请求崩溃。
            return None

        return plan, ctx

    async def list_checkpoints(self) -> list[dict[str, Any]]:
        """列出所有可恢复的工作流。"""
        checkpoints = []
        for f in sorted(self._dir.glob("*.json"), key=os.path.getmtime, reverse=True):
            try:
                data = json.loads(f.read_text(encoding="utf-8", errors="ignore"))
                plan = data.get("plan", {})
                steps = plan.get("steps", [])
                # replan 将被替代的失败步骤标为 skipped;已收敛的工作流不应再出现在「可恢复」列表里
                completed = sum(1 for s in steps if s.get("status") in {"completed", "skipped"})
                total = len(steps)
                checkpoints.append(
                    {
                        "workflow_id": data["workflow_id"],
                        "saved_at": data.get("saved_at_iso", ""),
                        "intent": plan.get("intent", "")[:100],
                        "goal": plan.get("goal", "")[:100],
                        "progress": f"{completed}/{total}",
                        "c_id": data.get("context", {}).get("metadata", {}).get("c_id", ""),
                        "file": f.name,
                    }
                )
            except Exception:
                continue
        return checkpoints

    async def delete(self, workflow_id: str) -> bool:
        """删除指定工作流的 checkpoint。"""
        filepath = self._dir / f"{workflow_id}.json"
        if filepath.is_file():
            filepath.unlink()
            return True
        return False

    # ── 序列化辅助 ──

    @staticmethod
    def _coerce_positive_int(value: Any) -> int | None:
        """整数值原样收,整值 float(json 3.0)收为 int;其余(含 bool/负数)拒绝。"""
        if isinstance(value, bool):
            return None
        if isinstance(value, int):
            return value if value >= 1 else None
        if isinstance(value, float) and value.is_integer():
            return int(value) if value >= 1 else None
        return None

    def _plan_to_dict(self, plan: WorkflowPlan) -> dict:
        return {
            "workflow_id": plan.workflow_id,
            "intent": plan.intent,
            "goal": plan.goal,
            "max_concurrency": plan.max_concurrency,
            "verify_enabled": plan.verify_enabled,
            "metadata": plan.metadata,
            "steps": [self._step_to_dict(step) for step in plan.steps],
        }

    def _step_to_dict(self, step: WorkflowStep) -> dict:
        # 仅递归步骤结构,结果和 params 继续使用原 JSON/default=str 编码。
        # 不对任意工具结果做 dataclass 深拷贝或转换。
        values = {f.name: getattr(step, f.name) for f in fields(step)}
        if step.parallel_steps is not None:
            values["parallel_steps"] = [self._step_to_dict(child) for child in step.parallel_steps]
        return values

    def _step_from_dict(self, data: dict) -> WorkflowStep:
        if not isinstance(data, dict):
            raise ValueError("Invalid checkpoint step")
        raw_id = data.get("id")
        if isinstance(raw_id, bool) or not isinstance(raw_id, (str, int, float)):
            raise ValueError("Invalid checkpoint step id")
        values = {f.name: data[f.name] for f in fields(WorkflowStep) if f.name in data}
        # id 归一为 str:save 端 json 原生序列化会把 planner 透传的非 str id 原样落盘
        values["id"] = str(int(raw_id)) if isinstance(raw_id, float) and raw_id.is_integer() else str(raw_id)
        values["type"] = StepType(data.get("type", "claude_skill"))
        values["status"] = StepStatus(data.get("status", "pending"))
        values.setdefault("name", "")
        # params=None 是 planner 对 LLM 输出 s.get("params", {}) 的合法透传(JSON null)
        if data.get("params") is None:
            values.pop("params", None)
        elif not isinstance(data["params"], dict):
            raise ValueError("Invalid checkpoint step params")
        for key, default in (("attempts", 0), ("max_retries", 2)):
            value = data.get(key, default)
            if type(value) is not int or value < 0:
                raise ValueError("Invalid checkpoint retry counter")
        deps = data.get("depends_on")
        if deps is None:
            values.pop("depends_on", None)
        elif not isinstance(deps, list) or any(isinstance(dep, bool) for dep in deps):
            raise ValueError("Invalid checkpoint step dependencies")
        else:
            # 依赖 id 与步骤 id 同规整:planner 会透传非 str 依赖(depends_on=[2])
            values["depends_on"] = [
                dep
                if isinstance(dep, str)
                else str(int(dep))
                if isinstance(dep, float) and dep.is_integer()
                else str(dep)
                for dep in deps
            ]
        children = data.get("parallel_steps")
        if children is not None:
            if not isinstance(children, list):
                raise ValueError("Invalid checkpoint parallel steps")
            values["parallel_steps"] = [self._step_from_dict(child) for child in children]
        return WorkflowStep(**values)

    def _context_to_dict(self, ctx: ExecutionContext) -> dict:
        return {
            "workflow_id": ctx.workflow_id,
            "variables": ctx.variables,
            "step_results": ctx.step_results,
            "errors": ctx.errors,
            "metadata": ctx.metadata,
        }