"""
Gestion de la configuration persistante dans ~/.config/alerte-sms/
Supporte : Telegram, Gmail, Discord
"""
import json
import os
from pathlib import Path


CONFIG_DIR  = Path.home() / ".config" / "alerte-sms"
CONFIG_FILE = CONFIG_DIR / "config.json"
EVENTS_FILE = CONFIG_DIR / "events.json"

PROVIDERS = ["telegram", "gmail", "discord"]


def ensure_config_dir():
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)


# ── Config generale ───────────────────────────────────────────────────────────

def load_config() -> dict:
    ensure_config_dir()
    if CONFIG_FILE.exists():
        with open(CONFIG_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return {}


def save_config(data: dict):
    ensure_config_dir()
    with open(CONFIG_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    os.chmod(CONFIG_FILE, 0o600)


def get_provider() -> str | None:
    return load_config().get("provider")


def set_provider(provider: str):
    config = load_config()
    config["provider"] = provider
    save_config(config)


# ── Config Telegram ───────────────────────────────────────────────────────────

def save_telegram_config(token: str, chat_ids: list):
    config = load_config()
    config["telegram"] = {"token": token, "chat_ids": chat_ids}
    save_config(config)


def load_telegram_config() -> dict:
    return load_config().get("telegram", {})


# ── Config Gmail ──────────────────────────────────────────────────────────────

def save_gmail_config(address: str, app_password: str):
    config = load_config()
    config["gmail"] = {"address": address, "app_password": app_password}
    save_config(config)


def load_gmail_config() -> dict:
    return load_config().get("gmail", {})


# ── Config Discord ────────────────────────────────────────────────────────────

def save_discord_config(webhook_urls: list):
    config = load_config()
    config["discord"] = {"webhook_urls": webhook_urls}
    save_config(config)


def load_discord_config() -> dict:
    return load_config().get("discord", {})


# ── Evenements ────────────────────────────────────────────────────────────────

def load_events() -> list:
    ensure_config_dir()
    if EVENTS_FILE.exists():
        with open(EVENTS_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return []


def save_events(events: list):
    ensure_config_dir()
    with open(EVENTS_FILE, "w", encoding="utf-8") as f:
        json.dump(events, f, indent=2, ensure_ascii=False)


def add_event(event: dict):
    events = load_events()
    events.append(event)
    save_events(events)


def remove_event(event_id: str):
    events = [e for e in load_events() if e.get("id") != event_id]
    save_events(events)
