"""Authentication helpers for the ugly-bot CLI."""

import json
import os
from dataclasses import dataclass
from typing import Optional


CONFIG_DIR = os.path.expanduser("~/.ugly-bot")
AUTH_FILE = os.path.join(CONFIG_DIR, "auth.json")


@dataclass
class AuthConfig:
    token: str
    userId: str
    serverUrl: str


def get_auth() -> Optional[AuthConfig]:
    """Read stored auth config from ~/.ugly-bot/auth.json"""
    if not os.path.exists(AUTH_FILE):
        return None
    try:
        with open(AUTH_FILE, "r") as f:
            data = json.load(f)
        return AuthConfig(
            token=data["token"],
            userId=data["userId"],
            serverUrl=data["serverUrl"],
        )
    except (json.JSONDecodeError, KeyError):
        return None


def save_auth(token: str, userId: str, serverUrl: str) -> None:
    """Save auth config to ~/.ugly-bot/auth.json"""
    os.makedirs(CONFIG_DIR, exist_ok=True)
    with open(AUTH_FILE, "w") as f:
        json.dump(
            {"token": token, "userId": userId, "serverUrl": serverUrl},
            f,
            indent=2,
        )


def clear_auth() -> None:
    """Remove stored auth config."""
    if os.path.exists(AUTH_FILE):
        os.remove(AUTH_FILE)
