"""
startup_wizard — guided first-run setup for GoldAutoTrade.

Tracks setup progress across these steps:
  1. MT5 安装检测
  2. MT5 桥接部署
  3. AI API Key 配置
  4. 试用授权激活
  5. 系统健康检查
  6. 完成

Persists progress so users can resume after restart.
"""

from __future__ import annotations

import json
import os
import time
from pathlib import Path
from typing import Any

try:
    from config_manager import get_app_dir
    APP_DIR = get_app_dir()
except Exception:
    APP_DIR = Path(os.environ.get("APPDATA", os.path.expanduser("~"))) / "GoldAutoTrade"

WIZARD_FILE = APP_DIR / "data" / "wizard_state.json"


def _read() -> dict[str, Any]:
    try:
        if WIZARD_FILE.exists():
            return json.loads(WIZARD_FILE.read_text(encoding="utf-8"))
    except Exception:
        pass
    return {"steps": {}, "started": False, "completed": False}


def _write(state: dict[str, Any]) -> None:
    WIZARD_FILE.parent.mkdir(parents=True, exist_ok=True)
    WIZARD_FILE.write_text(json.dumps(state, ensure_ascii=False, indent=2))


def get_wizard_status() -> dict[str, Any]:
    """Return current wizard status for the frontend."""
    state = _read()
    steps = _all_steps(state)
    completed_count = sum(1 for s in steps if s["status"] == "done")
    return {
        "started": state.get("started", False),
        "completed": state.get("completed", False),
        "steps": steps,
        "progress": round(completed_count / max(len(steps), 1) * 100),
        "ready": state.get("completed", False),
    }


def start_wizard() -> dict[str, Any]:
    """Mark wizard as started."""
    state = _read()
    state["started"] = True
    state["started_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    _write(state)
    return get_wizard_status()


def mark_step_done(step_id: str, detail: str = "") -> dict[str, Any]:
    """Mark a wizard step as completed."""
    state = _read()
    state.setdefault("steps", {})[step_id] = {
        "status": "done",
        "detail": detail,
        "completed_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    }
    # Check if all steps done
    all_ids = {"mt5_detect", "bridge_deploy", "api_key", "license", "health"}
    state_done = all(
        state["steps"].get(sid, {}).get("status") == "done"
        for sid in all_ids
    )
    if state_done:
        state["completed"] = True
    _write(state)
    return get_wizard_status()


def mark_step_failed(step_id: str, reason: str) -> dict[str, Any]:
    """Mark a wizard step as failed (user needs to take action)."""
    state = _read()
    state.setdefault("steps", {})[step_id] = {
        "status": "failed",
        "reason": reason,
        "failed_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    }
    _write(state)
    return get_wizard_status()


def _all_steps(state: dict[str, Any]) -> list[dict[str, Any]]:
    saved = state.get("steps", {})

    # Step 1: MT5 detection
    mt5_found = False
    mt5_path = ""
    try:
        from config_manager import get_mt5_dir
        p = get_mt5_dir()
        mt5_found = p.exists()
        mt5_path = str(p)
    except Exception:
        pass

    step1 = saved.get("mt5_detect", {})
    if step1.get("status") != "done" and mt5_found:
        step1 = {"status": "done", "detail": f"已检测到 MT5: {mt5_path}"}
    elif not step1:
        step1 = {
            "status": "pending" if not mt5_found else "done",
            "detail": f"已检测到 MT5: {mt5_path}" if mt5_found else "未检测到 MT5，请在 设置→MT5路径 中手动配置",
            "mt5_path": mt5_path,
        }

    # Step 2: Bridge deployment
    bridge_ok = False
    bridge_detail = ""
    try:
        p = Path(mt5_path) if mt5_path else None
        if p and (p / "gold_autotrade" / "bridge" / "to_ea").exists():
            bridge_ok = True
            bridge_detail = "桥接目录已就绪"
        elif p and (p / "gold_autotrade" / "bridge").exists():
            bridge_ok = True
            bridge_detail = "桥接目录已创建，等待 EA 编译并附加到图表"
        else:
            bridge_detail = "桥接目录未创建。配置 MT5 路径后将自动创建。"
    except Exception:
        bridge_detail = "桥接状态未知"

    step2 = saved.get("bridge_deploy", {})
    if step2.get("status") != "done" and bridge_ok:
        step2 = {"status": "done", "detail": bridge_detail}
    elif not step2:
        step2 = {"status": "pending", "detail": bridge_detail}

    # Step 3: API Key
    has_key = False
    key_detail = ""
    try:
        import config_manager
        llm_dir = config_manager.get_llm_config_dir()
        for cfg_path in (llm_dir / "openclaw.json", Path.home() / ".openclaw" / "openclaw.json"):
            if cfg_path.exists():
                cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
                providers = cfg.get("models", {}).get("providers", {})
                configured = [n for n, i in providers.items() if i.get("apiKey", "")]
                if configured:
                    has_key = True
                    key_detail = f"已配置: {', '.join(configured)}"
                    break
    except Exception:
        pass
    if not has_key:
        key_detail = "未配置 API Key。请在 设置→大模型配置 中添加。"

    step3 = saved.get("api_key", {})
    if step3.get("status") != "done" and has_key:
        step3 = {"status": "done", "detail": key_detail}
    elif not step3:
        step3 = {"status": "pending", "detail": key_detail}

    # Step 4: License
    lic_ok = False
    lic_detail = ""
    try:
        from src.license.validator import get_license_status
        status = get_license_status()
        if status.get("status") == "ACTIVE":
            lic_ok = True
            lic_detail = f"授权有效: {status.get('tier','trial')} / 到期: {status.get('expires','')}"
        elif status.get("status") == "TRIAL_ACTIVE":
            lic_ok = True
            lic_detail = f"试用授权有效，剩余 {status.get('days_left', 0)} 天"
        else:
            lic_detail = f"授权状态: {status.get('status','UNKNOWN')} — {status.get('message','')}"
    except Exception:
        lic_detail = "授权状态未知"

    step4 = saved.get("license", {})
    if step4.get("status") != "done" and lic_ok:
        step4 = {"status": "done", "detail": lic_detail}
    elif not step4:
        step4 = {"status": "pending", "detail": lic_detail}

    # Step 5: Health check summary
    health_ok = state.get("completed", False)
    health_detail = ""
    total = len([s for s in [step1, step2, step3, step4] if s["status"] == "done"])
    if total >= 4:
        health_ok = True
        health_detail = f"全部就绪 ({total}/4 通过)"
    else:
        health_detail = f"{total}/4 项就绪，继续完成剩余步骤"

    step5 = saved.get("health", {})
    if not step5:
        step5 = {"status": "done" if health_ok else "pending", "detail": health_detail}

    return [
        {"id": "mt5_detect", "name": "MT5 安装检测", "icon": "search", **step1},
        {"id": "bridge_deploy", "name": "桥接部署", "icon": "link", **step2},
        {"id": "api_key", "name": "AI 大模型配置", "icon": "key", **step3},
        {"id": "license", "name": "授权激活", "icon": "shield", **step4},
        {"id": "health", "name": "系统就绪", "icon": "check", **step5},
    ]
