"""Where per-account state lives on disk.

State is keyed by (Control Room URL, username) so two accounts on the same
Control Room — or the same account across two Control Rooms — never share a
token file or a session ledger.
"""

import hashlib
import os
import re
from pathlib import Path

STATE_DIR_ENV = "A360_MCP_STATE_DIR"
DEFAULT_STATE_DIR_NAME = ".a360_mcp"
ACCOUNT_KEY_LENGTH = 16
_UNSAFE_LABEL_CHARS = re.compile(r"[^A-Za-z0-9._-]+")


def state_dir() -> Path:
    """Root directory for token caches, session ledgers and lock files."""
    override = os.environ.get(STATE_DIR_ENV)
    if override:
        return Path(override).expanduser()
    return Path.home() / DEFAULT_STATE_DIR_NAME


def account_key(control_room_url: str, username: str) -> str:
    """Stable, filesystem-safe identifier for one account on one Control Room.

    The readable prefix keeps state files diagnosable by eye; the hash suffix
    keeps them unique when hosts differ only past the truncation point.
    """
    normalized = f"{control_room_url.rstrip('/').lower()}|{username.strip().lower()}"
    digest = hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:ACCOUNT_KEY_LENGTH]
    label = _UNSAFE_LABEL_CHARS.sub("-", username.strip().lower()).strip("-") or "account"
    return f"{label[:24]}-{digest}"


def token_path(key: str) -> Path:
    return state_dir() / f"token_{key}.json"


def session_ledger_path(key: str) -> Path:
    return state_dir() / f"sessions_{key}.json"


def lock_path(key: str, purpose: str) -> Path:
    return state_dir() / f"{purpose}_{key}.lock"
