"""
Centralized path constants for SooSeF.

All ~/.soosef/* paths are defined here. Every module that needs a path
imports from this module — no hardcoded paths anywhere else.

The base directory can be overridden via:
- SOOSEF_DATA_DIR environment variable (before import)
- Setting paths.BASE_DIR at runtime (e.g., CLI --data-dir flag)

All derived paths (IDENTITY_DIR, CHAIN_DIR, etc.) are computed lazily
from BASE_DIR so that runtime overrides propagate correctly.
"""

import os
from pathlib import Path

# Allow override for testing or multi-instance deployments
BASE_DIR = Path(os.environ.get("SOOSEF_DATA_DIR", Path.home() / ".soosef"))

# Path definitions relative to BASE_DIR. These are resolved lazily via
# __getattr__ so that changes to BASE_DIR propagate to all derived paths.
_PATH_DEFS: dict[str, tuple[str, ...]] = {
    # Ed25519 identity keypair (verisoo signing)
    "IDENTITY_DIR": ("identity",),
    "IDENTITY_PRIVATE_KEY": ("identity", "private.pem"),
    "IDENTITY_PUBLIC_KEY": ("identity", "public.pem"),
    # Sidecar metadata written by generate_identity(); stores creation timestamp
    # so get_identity() can return an authoritative created_at without relying
    # on fragile filesystem mtime.
    "IDENTITY_META": ("identity", "identity.meta.json"),
    # Stegasoo state
    "STEGASOO_DIR": ("stegasoo",),
    "CHANNEL_KEY_FILE": ("stegasoo", "channel.key"),
    # Verisoo attestation storage
    "ATTESTATIONS_DIR": ("attestations",),
    "ATTESTATION_LOG": ("attestations", "log.bin"),
    "ATTESTATION_INDEX": ("attestations", "index"),
    "PEERS_FILE": ("attestations", "peers.json"),
    # Web UI auth database
    "AUTH_DIR": ("auth",),
    "AUTH_DB": ("auth", "soosef.db"),
    # SSL certificates
    "CERTS_DIR": ("certs",),
    "SSL_CERT": ("certs", "cert.pem"),
    "SSL_KEY": ("certs", "key.pem"),
    # Fieldkit state
    "FIELDKIT_DIR": ("fieldkit",),
    "FIELDKIT_CONFIG": ("fieldkit", "config.json"),
    "DEADMAN_STATE": ("fieldkit", "deadman.json"),
    "TAMPER_DIR": ("fieldkit", "tamper"),
    "TAMPER_BASELINE": ("fieldkit", "tamper", "baseline.json"),
    "USB_DIR": ("fieldkit", "usb"),
    "USB_WHITELIST": ("fieldkit", "usb", "whitelist.json"),
    "GEOFENCE_CONFIG": ("fieldkit", "geofence.json"),
    # Attestation hash chain
    "CHAIN_DIR": ("chain",),
    "CHAIN_DB": ("chain", "chain.bin"),
    "CHAIN_STATE": ("chain", "state.cbor"),
    # Ephemeral
    "TEMP_DIR": ("temp",),
    # Structured audit trail (append-only JSON-lines).
    # Lives directly under BASE_DIR so it is destroyed by the killswitch along
    # with everything else — intentional, per the security model.
    "AUDIT_LOG": ("audit.jsonl",),
    # Flask instance path (sessions, secret key)
    "INSTANCE_DIR": ("instance",),
    "SECRET_KEY_FILE": ("instance", ".secret_key"),
    # Unified config
    "CONFIG_FILE": ("config.json",),
}


def __getattr__(name: str) -> Path:
    """Resolve derived paths lazily from current BASE_DIR."""
    if name in _PATH_DEFS:
        return Path(BASE_DIR, *_PATH_DEFS[name])
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


def ensure_dirs() -> None:
    """Create all required directories with appropriate permissions."""
    dirs = [
        BASE_DIR,
        __getattr__("IDENTITY_DIR"),
        __getattr__("STEGASOO_DIR"),
        __getattr__("ATTESTATIONS_DIR"),
        __getattr__("CHAIN_DIR"),
        __getattr__("AUTH_DIR"),
        __getattr__("CERTS_DIR"),
        __getattr__("FIELDKIT_DIR"),
        __getattr__("TAMPER_DIR"),
        __getattr__("USB_DIR"),
        __getattr__("TEMP_DIR"),
        __getattr__("INSTANCE_DIR"),
    ]
    for d in dirs:
        d.mkdir(parents=True, exist_ok=True)

    # Restrict permissions on sensitive directories
    for d in [
        BASE_DIR,
        __getattr__("IDENTITY_DIR"),
        __getattr__("AUTH_DIR"),
        __getattr__("CERTS_DIR"),
    ]:
        d.chmod(0o700)
