"""Gerenciamento de configuração (~/.config/tecjustica/config.toml)."""

from __future__ import annotations

import os
from pathlib import Path
from typing import Any

import tomli_w

CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "tecjustica"
CONFIG_FILE = CONFIG_DIR / "config.toml"

DEFAULT_SERVER_URL = "https://mcp.tecjustica.com/mcp"
SUPABASE_URL = "https://pglghyznirxkewcmuhvp.supabase.co"
SUPABASE_ANON_KEY = (
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
    "eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InBnbGdoeXpuaXJ4a2V3Y211aHZwIiwi"
    "cm9sZSI6ImFub24iLCJpYXQiOjE3NjYzNjk4MTgsImV4cCI6MjA4MTk0NTgxOH0."
    "hac05fv66miyiRqzwBIZYSA8gjA8dcRFOJMs3wSqWpA"
)


def _read_config() -> dict[str, Any]:
    """Lê config.toml. Retorna dict vazio se não existir."""
    if not CONFIG_FILE.exists():
        return {}
    import tomllib

    return tomllib.loads(CONFIG_FILE.read_text())


def _write_config(data: dict[str, Any]) -> None:
    """Escreve config.toml, criando diretório se necessário."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    CONFIG_FILE.write_bytes(tomli_w.dumps(data).encode())


def save_token(token: str) -> None:
    """Salva token de autenticação."""
    config = _read_config()
    config["token"] = token
    _write_config(config)


def get_token() -> str | None:
    """Resolve token: env TECJUSTICA_TOKEN > config.toml > None."""
    env_token = os.environ.get("TECJUSTICA_TOKEN")
    if env_token:
        return env_token
    config = _read_config()
    return config.get("token")


def get_server_url() -> str:
    """Resolve URL do servidor: env > config > default."""
    env_url = os.environ.get("TECJUSTICA_SERVER_URL")
    if env_url:
        return env_url
    config = _read_config()
    return config.get("server_url", DEFAULT_SERVER_URL)


def remove_token() -> None:
    """Remove token da config."""
    config = _read_config()
    config.pop("token", None)
    _write_config(config)
