from __future__ import annotations

import os
import uuid
from pathlib import Path

from aicd.config import AppConfig, load_config, save_config


def default_home() -> Path:
    """未设置 AICD_HOME 且未传 --home 时，使用当前用户主目录下的 ``~/.aicd``。"""
    env = os.environ.get("AICD_HOME")
    if env:
        return Path(env).expanduser().resolve()
    return (Path.home() / ".aicd").resolve()


def home_paths(root: Path) -> dict[str, Path]:
    return {
        "root": root,
        "config": root / "config.yaml",
        "data": root / "data",
        "db": root / "data" / "app.db",
        "tasks": root / "tasks",
        "cache": root / "cache",
        "logs": root / "logs",
        "tmp_scripts": root / "tmp" / "scripts",
    }


def new_chat_session_id(data_dir: Path) -> str:
    """生成新的主会话 UUID 并写入 ``data/active_chat_session_id.txt``（每次调用均换新 id）。"""
    data_dir.mkdir(parents=True, exist_ok=True)
    path = data_dir / "active_chat_session_id.txt"
    sid = str(uuid.uuid4())
    path.write_text(sid, encoding="utf-8")
    return sid


def ensure_home_layout(root: Path) -> dict[str, Path]:
    paths = home_paths(root)
    root.mkdir(parents=True, exist_ok=True)
    for key in ("data", "tasks", "cache", "logs", "tmp_scripts"):
        paths[key].mkdir(parents=True, exist_ok=True)
    return paths


def init_home(root: Path | None = None) -> tuple[Path, dict[str, Path], AppConfig]:
    r = root or default_home()
    layout = ensure_home_layout(r)
    cfg_path = layout["config"]
    if not cfg_path.is_file():
        save_config(cfg_path, AppConfig())
    cfg = load_config(cfg_path)
    return r, layout, cfg
