"""Configuration management for ReplyMarketing CLI."""

from __future__ import annotations

import json
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Optional


def _default_skills() -> dict[str, Any]:
    return {"auto_update": True, "last_update": ""}


def _default_preferences() -> dict[str, Any]:
    return {"confirm_before_submit": True}


@dataclass
class Config:
    version: str = "1.0.0"
    provider: Optional[dict[str, Any]] = None
    skills: dict[str, Any] = field(default_factory=_default_skills)
    preferences: dict[str, Any] = field(default_factory=_default_preferences)


# XDG Config paths
CONFIG_DIR = Path.home() / ".config" / "replycash"
CREDENTIALS_PATH = CONFIG_DIR / "credentials.json"
CONFIG_PATH = CONFIG_DIR / "config.json"

# App data paths
DATA_DIR = Path.home() / ".replycash"
SKILLS_DIR = DATA_DIR / "skills"
SCHEDULES_DIR = DATA_DIR / "schedules"
CODE_DIR = DATA_DIR / "code"


def ensure_config_dir() -> None:
    """Ensure all config directories exist."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    SKILLS_DIR.mkdir(parents=True, exist_ok=True)
    SCHEDULES_DIR.mkdir(parents=True, exist_ok=True)
    CODE_DIR.mkdir(parents=True, exist_ok=True)


def load_config() -> Config:
    """Load configuration from file."""
    try:
        with open(CONFIG_PATH, "r") as f:
            data = json.load(f)
            return Config(**data)
    except (FileNotFoundError, json.JSONDecodeError):
        return Config()


def save_config(config: Config) -> None:
    """Save configuration to file."""
    ensure_config_dir()
    with open(CONFIG_PATH, "w") as f:
        json.dump(config.__dict__, f, indent=2)


def load_credentials() -> Optional[dict[str, Any]]:
    """Load credentials from file."""
    try:
        with open(CREDENTIALS_PATH, "r") as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        return None


def save_credentials(credentials: dict[str, Any]) -> None:
    """Save credentials to file with restricted permissions."""
    ensure_config_dir()
    with open(CREDENTIALS_PATH, "w") as f:
        json.dump(credentials, f, indent=2)
    # Set restrictive permissions (Unix only)
    try:
        os.chmod(CREDENTIALS_PATH, 0o600)
    except (OSError, NotImplementedError):
        pass
