"""
Unified configuration for SooSeF.

Loads from ~/.soosef/config.json with environment variable overrides.
Config is intentionally simple — a flat JSON file with sensible defaults.
"""

import json
from dataclasses import dataclass
from pathlib import Path

import soosef.paths as _paths


@dataclass
class SoosefConfig:
    """Runtime configuration for SooSeF."""

    # Web UI
    host: str = "127.0.0.1"
    port: int = 5000
    https_enabled: bool = True
    auth_enabled: bool = True
    max_upload_mb: int = 50
    session_timeout_minutes: int = 15
    login_lockout_attempts: int = 5
    login_lockout_minutes: int = 15

    # Stegasoo defaults
    default_embed_mode: str = "auto"

    # Fieldkit
    killswitch_enabled: bool = False
    deadman_enabled: bool = False
    deadman_interval_hours: int = 24
    deadman_grace_hours: int = 2
    deadman_warning_webhook: str = ""  # URL to POST warning before auto-purge
    usb_monitoring_enabled: bool = False
    tamper_monitoring_enabled: bool = False

    # Attestation chain
    chain_enabled: bool = True
    chain_auto_wrap: bool = True  # Auto-wrap verisoo attestations in chain records

    # Backup
    backup_reminder_days: int = 7  # Warn if no backup in this many days

    # Cover/duress mode
    cover_name: str = ""  # If set, used for SSL cert CN instead of "SooSeF Local"

    # Hardware (RPi)
    gpio_killswitch_pin: int = 17
    gpio_killswitch_hold_seconds: float = 5.0

    @classmethod
    def load(cls, path: Path | None = None) -> "SoosefConfig":
        """Load config from JSON file, falling back to defaults."""
        config_path = path or _paths.CONFIG_FILE
        if config_path.exists():
            with open(config_path) as f:
                data = json.load(f)
            return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
        return cls()

    def save(self, path: Path | None = None) -> None:
        """Persist config to JSON file."""
        config_path = path or _paths.CONFIG_FILE
        config_path.parent.mkdir(parents=True, exist_ok=True)
        from dataclasses import asdict

        with open(config_path, "w") as f:
            json.dump(asdict(self), f, indent=2)
