"""Stable, non-roaming licensing data paths independent of GUI imports."""

from __future__ import annotations

from dataclasses import dataclass
import os
from pathlib import Path
import sys
from typing import Mapping, Optional

from .constants import CANONICAL_PRODUCT_DIRECTORY, LICENSING_ORGANIZATION_DIRECTORY


@dataclass(frozen=True)
class LicensingPaths:
    root: Path
    entitlement_snapshot: Path
    offline_license: Path
    public_state: Path
    protected_state: Path
    protected_update_state: Path
    update_downloads: Path

    def __post_init__(self) -> None:
        if not isinstance(self.root, Path):
            raise TypeError("root must be a Path")
        for field_name in (
            "entitlement_snapshot",
            "offline_license",
            "public_state",
            "protected_state",
            "protected_update_state",
            "update_downloads",
        ):
            value = getattr(self, field_name)
            if not isinstance(value, Path):
                raise TypeError(f"{field_name} must be a Path")
            if value.parent != self.root:
                raise ValueError(f"{field_name} must be directly inside the licensing root")


def default_licensing_paths(
    *,
    environment: Optional[Mapping[str, str]] = None,
    home: Optional[str | Path] = None,
    platform_name: Optional[str] = None,
) -> LicensingPaths:
    if environment is not None and not isinstance(environment, Mapping):
        raise TypeError("environment must be a mapping or None")
    env = os.environ if environment is None else environment
    if home is None:
        home_path = Path.home()
    elif isinstance(home, (str, os.PathLike)):
        home_path = Path(home)
    else:
        raise TypeError("home must be a string, path-like value, or None")
    platform_value = sys.platform if platform_name is None else platform_name
    if not isinstance(platform_value, str) or not platform_value.strip():
        raise ValueError("platform_name must be a non-empty string or None")
    if platform_value.lower().startswith("win"):
        configured = str(env.get("LOCALAPPDATA") or "").strip()
        base = Path(configured) if configured else home_path / "AppData" / "Local"
    else:
        configured = str(env.get("XDG_DATA_HOME") or "").strip()
        base = Path(configured) if configured else home_path / ".local" / "share"
    root = base / LICENSING_ORGANIZATION_DIRECTORY / CANONICAL_PRODUCT_DIRECTORY / "licensing"
    return LicensingPaths(
        root=root,
        entitlement_snapshot=root / "entitlement.json",
        offline_license=root / "offline-license.json",
        public_state=root / "state.json",
        protected_state=root / "protected-state.bin",
        protected_update_state=root / "protected-update-state.bin",
        update_downloads=root / "updates",
    )


__all__ = ["LicensingPaths", "default_licensing_paths"]
