from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Mapping

APP_DIR_NAME = "IuVeConnectAgent"
CONFIG_FILE_NAME = "config.json"
IDENTITY_FILE_NAME = "identity.json"
RUNTIME_STATE_FILE_NAME = "runtime_state.json"
LOG_FILE_NAME = "agent.log"


@dataclass(slots=True)
class WindowsAdapterPaths:
    appdata_root: Path
    local_appdata_root: Path
    install_root: Path
    storage_root: Path
    logs_dir: Path
    config_path: Path
    local_identity_path: Path
    runtime_state_path: Path

    def to_safe_dict(self) -> dict[str, str]:
        return {
            "appdata_root": str(self.appdata_root),
            "local_appdata_root": str(self.local_appdata_root),
            "install_root": str(self.install_root),
            "storage_root": str(self.storage_root),
            "logs_dir": str(self.logs_dir),
            "config_path": str(self.config_path),
            "local_identity_path": str(self.local_identity_path),
            "runtime_state_path": str(self.runtime_state_path),
        }


def _expand(raw: str) -> Path:
    return Path(raw).expanduser().resolve()


def build_windows_paths(env: Mapping[str, str] | None = None) -> WindowsAdapterPaths:
    source = dict(env) if env is not None else {}

    appdata_raw = source.get("APPDATA") or "~\\AppData\\Roaming"
    local_appdata_raw = source.get("LOCALAPPDATA") or "~\\AppData\\Local"

    appdata_root = _expand(appdata_raw)
    local_appdata_root = _expand(local_appdata_raw)

    install_root = local_appdata_root / APP_DIR_NAME
    storage_root = appdata_root / APP_DIR_NAME
    logs_dir = storage_root / "logs"
    config_path = storage_root / CONFIG_FILE_NAME
    local_identity_path = storage_root / IDENTITY_FILE_NAME
    runtime_state_path = storage_root / RUNTIME_STATE_FILE_NAME

    return WindowsAdapterPaths(
        appdata_root=appdata_root,
        local_appdata_root=local_appdata_root,
        install_root=install_root,
        storage_root=storage_root,
        logs_dir=logs_dir,
        config_path=config_path,
        local_identity_path=local_identity_path,
        runtime_state_path=runtime_state_path,
    )
