"""客户端本机 session 存储 —— 0.1 期写 `~/.xiangqin/session.json`。

未来要迁移到 vault（`vault set xiangqin session_token ...`），但 0.1 不强依赖 vault CLI
在客户端电脑已装的假设。
"""

from __future__ import annotations

import json
import os
from pathlib import Path

SESSION_DIR = Path(os.environ.get("XIANGQIN_CONFIG_DIR", str(Path.home() / ".xiangqin")))
SESSION_FILE = SESSION_DIR / "session.json"


def save(session_token: str, user_id: str, endpoint: str, masked_phone: str) -> None:
    SESSION_DIR.mkdir(mode=0o700, exist_ok=True)
    SESSION_FILE.write_text(
        json.dumps(
            {
                "session_token": session_token,
                "user_id": user_id,
                "endpoint": endpoint,
                "masked_phone": masked_phone,
            },
            ensure_ascii=False,
            indent=2,
        )
    )
    SESSION_FILE.chmod(0o600)


def load() -> dict[str, str] | None:
    if not SESSION_FILE.exists():
        return None
    try:
        return json.loads(SESSION_FILE.read_text())
    except (OSError, json.JSONDecodeError):
        return None


def clear() -> None:
    SESSION_FILE.unlink(missing_ok=True)
