"""
Neura Runtime Configuration.

Stores settings in ~/.neura/config.json.
"""
import os
import json
from pathlib import Path
from dataclasses import dataclass, field, asdict
from typing import Optional, List

NEURA_DIR = Path.home() / ".neura"
CONFIG_FILE = NEURA_DIR / "config.json"
DEVICE_TOKEN_FILE = NEURA_DIR / "device_token"


@dataclass
class RuntimeConfig:
    """Runtime configuration with sensible defaults."""

    # Connection
    cloud_url: str = "https://app.neura.ai"
    cloud_ws_url: str = "wss://app.neura.ai/runtime/ws"
    health_port: int = 9700

    # Docker
    docker_memory_limit: str = "1g"
    docker_cpu_limit: float = 2.0
    docker_network_default: str = "none"

    # Streamlit
    streamlit_port_start: int = 8501
    streamlit_port_end: int = 8520

    # Ollama
    ollama_url: str = "http://localhost:11434"
    lm_studio_url: str = "http://localhost:1234"

    # File access
    allowed_directories: List[str] = field(default_factory=list)

    # Device
    device_name: Optional[str] = None
    device_id: Optional[str] = None
    paired: bool = False

    def save(self):
        """Save config to disk."""
        NEURA_DIR.mkdir(parents=True, exist_ok=True)
        CONFIG_FILE.write_text(json.dumps(asdict(self), indent=2))

    @classmethod
    def load(cls) -> "RuntimeConfig":
        """Load config from disk, or create defaults."""
        if CONFIG_FILE.exists():
            try:
                data = json.loads(CONFIG_FILE.read_text())
                return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
            except (json.JSONDecodeError, TypeError):
                pass
        config = cls()
        config.save()
        return config


def get_device_token() -> Optional[str]:
    """Read the device token from disk."""
    if DEVICE_TOKEN_FILE.exists():
        return DEVICE_TOKEN_FILE.read_text().strip()
    return None


def save_device_token(token: str):
    """Save device token to disk."""
    NEURA_DIR.mkdir(parents=True, exist_ok=True)
    DEVICE_TOKEN_FILE.write_text(token)
    os.chmod(str(DEVICE_TOKEN_FILE), 0o600)
