#!/usr/bin/env python3
"""wx-quote-assistant — 会话状态管理

处理 session 目录创建、state.json 读写、checkpoint 签核、每日序号管理。

CLI 用法:
  python3 state_manager.py init --business <name> [--workspace <path>]
  python3 state_manager.py get-state --business <name> --session-id <id>
  python3 state_manager.py set-stage --business <name> --session-id <id> --stage <N>
  python3 state_manager.py sign-off --business <name> --session-id <id> --checkpoint <name>
"""

import argparse
import json
import os
import sys
from datetime import datetime


ROOT_DIR = os.path.expanduser("~/.wx-quote-assistant")


def _workspace(ws: str | None) -> str:
    return ws or os.getcwd()


def _business_dir(business_name: str) -> str:
    return os.path.join(ROOT_DIR, business_name)


def _session_dir(workspace: str, business_name: str, session_id: str) -> str:
    return os.path.join(workspace, "报价单", session_id, ".session")


def _state_path(workspace: str, business_name: str, session_id: str) -> str:
    return os.path.join(_session_dir(workspace, business_name, session_id), "state.json")


def _read_state(workspace: str, business_name: str, session_id: str) -> dict:
    path = _state_path(workspace, business_name, session_id)
    if not os.path.exists(path):
        print(json.dumps({"error": f"Session {session_id} not found for {business_name}"}), file=sys.stderr)
        sys.exit(1)
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def _write_state(workspace: str, business_name: str, session_id: str, state: dict) -> None:
    path = _state_path(workspace, business_name, session_id)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        json.dump(state, f, ensure_ascii=False, indent=2)


def cmd_init(args) -> None:
    """创建新报价会话。"""
    business_name = args.business
    workspace = args.workspace or os.getcwd()

    # 验证业务目录存在
    bd = _business_dir(business_name)
    if not os.path.isdir(bd):
        print(json.dumps({"error": f"Business '{business_name}' not initialized. Run stage 0 first."}), file=sys.stderr)
        sys.exit(1)

    # 生成 session_id
    session_id = datetime.now().strftime("%Y-%m-%d-%H%M%S")
    sd = _session_dir(workspace, business_name, session_id)

    state = {
        "session_id": session_id,
        "business_name": business_name,
        "workspace": workspace,
        "created_at": datetime.now().isoformat(),
        "current_stage": 1,
        "checkpoints": {
            "business_ready": {"signed": True, "at": None},
            "outline_confirmed": {"signed": False, "at": None},
            "draft_confirmed": {"signed": False, "at": None},
            "qa_choice": {"signed": False, "at": None},
            "delivery_complete": {"signed": False, "at": None},
        },
        "daily_seq": None,
    }

    os.makedirs(sd, exist_ok=True)
    with open(os.path.join(sd, "state.json"), "w", encoding="utf-8") as f:
        json.dump(state, f, ensure_ascii=False, indent=2)

    print(json.dumps({"ok": True, "session_id": session_id, "state_path": os.path.join(sd, "state.json")}, ensure_ascii=False))


def cmd_get_state(args) -> None:
    """读取当前会话状态。"""
    state = _read_state(_workspace(args.workspace), args.business, args.session_id)
    print(json.dumps(state, ensure_ascii=False, indent=2))


def cmd_set_stage(args) -> None:
    """更新当前阶段。"""
    state = _read_state(_workspace(args.workspace), args.business, args.session_id)
    stage = int(args.stage)
    state["current_stage"] = stage
    _write_state(_workspace(args.workspace), args.business, args.session_id, state)
    print(json.dumps({"ok": True, "current_stage": stage}, ensure_ascii=False))


def cmd_sign_off(args) -> None:
    """签核 checkpoint。"""
    state = _read_state(_workspace(args.workspace), args.business, args.session_id)
    checkpoint = args.checkpoint
    if checkpoint not in state["checkpoints"]:
        valid = list(state["checkpoints"].keys())
        print(json.dumps({"error": f"Unknown checkpoint '{checkpoint}'. Valid: {valid}"}, ensure_ascii=False), file=sys.stderr)
        sys.exit(1)
    state["checkpoints"][checkpoint] = {"signed": True, "at": datetime.now().isoformat()}
    _write_state(_workspace(args.workspace), args.business, args.session_id, state)
    print(json.dumps({"ok": True, "checkpoint": checkpoint, "signed_at": state["checkpoints"][checkpoint]["at"]}, ensure_ascii=False))


def main():
    parser = argparse.ArgumentParser(description="wx-quote-assistant State Manager")
    sub = parser.add_subparsers(dest="command", required=True)

    p_init = sub.add_parser("init", help="Initialize a new quote session")
    p_init.add_argument("--business", required=True)
    p_init.add_argument("--workspace", default=None)
    p_init.set_defaults(func=cmd_init)

    p_get = sub.add_parser("get-state", help="Get current session state")
    p_get.add_argument("--workspace", default=None)
    p_get.add_argument("--business", required=True)
    p_get.add_argument("--session-id", required=True)
    p_get.set_defaults(func=cmd_get_state)

    p_stage = sub.add_parser("set-stage", help="Set current stage")
    p_stage.add_argument("--workspace", default=None)
    p_stage.add_argument("--business", required=True)
    p_stage.add_argument("--session-id", required=True)
    p_stage.add_argument("--stage", required=True, type=int)
    p_stage.set_defaults(func=cmd_set_stage)

    p_sign = sub.add_parser("sign-off", help="Sign off a checkpoint")
    p_sign.add_argument("--workspace", default=None)
    p_sign.add_argument("--business", required=True)
    p_sign.add_argument("--session-id", required=True)
    p_sign.add_argument("--checkpoint", required=True)
    p_sign.set_defaults(func=cmd_sign_off)

    args = parser.parse_args()
    args.func(args)


if __name__ == "__main__":
    main()
