#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
from pathlib import Path


def load_workspace_config(workspace: Path) -> dict:
    config_path = workspace / ".config.json"
    if not config_path.is_file():
        raise FileNotFoundError(f"未找到 workspace 中的 .config.json: {config_path}")
    with config_path.open("r", encoding="utf-8") as f:
        return json.load(f)


def run_post_install(agent_id: str, workspace: Path) -> dict:
    if not workspace.is_dir():
        raise FileNotFoundError(f"workspace 目录不存在: {workspace}")

    config = load_workspace_config(workspace)
    if config.get("agent_id") != agent_id:
        raise ValueError(f"workspace 中 .config.json 的 agent_id ({config.get('agent_id')}) 与预期 ({agent_id}) 不一致")

    post_install = config.get("post_install")
    if not isinstance(post_install, list) or not post_install:
        return {
            "ok": True,
            "agent_id": agent_id,
            "workspace": str(workspace),
            "results": [],
            "message": "无 post_install 任务。",
        }

    results = []
    for item in post_install:
        if not isinstance(item, dict):
            continue

        name = item.get("name", "unnamed")
        script_rel = item.get("script", "")
        args = item.get("args", [])
        delete_on_success = item.get("delete_on_success", False)

        if not isinstance(script_rel, str) or not script_rel.strip():
            results.append({
                "name": name,
                "script": "",
                "success": False,
                "error": "script 字段为空",
            })
            continue

        script_path = (workspace / script_rel).resolve()

        if not script_path.is_file():
            results.append({
                "name": name,
                "script": str(script_path),
                "success": False,
                "error": f"脚本不存在: {script_path}",
            })
            continue

        cmd = [str(script_path)] + [str(a) for a in args] if isinstance(args, list) else [str(script_path)]

        try:
            proc = subprocess.run(
                cmd,
                cwd=str(workspace),
                env={**os.environ, "WORKSPACE": str(workspace)},
                capture_output=True,
                text=True,
                timeout=300,
            )
        except subprocess.TimeoutExpired:
            results.append({
                "name": name,
                "script": str(script_path),
                "success": False,
                "error": "脚本执行超时（300s）",
            })
            continue
        except OSError as e:
            results.append({
                "name": name,
                "script": str(script_path),
                "success": False,
                "error": f"无法执行脚本: {e}",
            })
            continue

        result_entry = {
            "name": name,
            "script": str(script_path),
            "success": proc.returncode == 0,
            "exit_code": proc.returncode,
            "stdout": proc.stdout.strip(),
            "stderr": proc.stderr.strip(),
        }

        if proc.returncode == 0:
            if delete_on_success:
                try:
                    script_path.unlink()
                    result_entry["deleted"] = True
                except OSError as e:
                    result_entry["deleted"] = False
                    result_entry["delete_error"] = str(e)
            else:
                result_entry["deleted"] = False
        else:
            result_entry["deleted"] = False

        results.append(result_entry)

        if proc.returncode != 0:
            return {
                "ok": False,
                "agent_id": agent_id,
                "workspace": str(workspace),
                "results": results,
                "message": f"post_install 脚本执行失败: {name} (exit={proc.returncode})",
            }

    return {
        "ok": True,
        "agent_id": agent_id,
        "workspace": str(workspace),
        "results": results,
        "message": "全部 post_install 脚本执行完成。",
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="执行 Agent 的 post_install 脚本")
    parser.add_argument("--agent-id", required=True, help="Agent ID")
    parser.add_argument("--workspace", required=True, help="目标 workspace 路径")
    args = parser.parse_args()

    workspace = Path(args.workspace).expanduser().resolve()
    result = run_post_install(args.agent_id, workspace)
    json.dump(result, sys.stdout, indent=2, ensure_ascii=False)
    sys.stdout.write("\n")
    return 0 if result["ok"] else 1


if __name__ == "__main__":
    raise SystemExit(main())