"""
Credential storage for SigmanticAI CLI.

Stores Supabase auth tokens at ~/.sigmanticai/credentials.json with mode 600.
"""

from __future__ import annotations

import json
import os
import stat
from pathlib import Path
from typing import Any, Dict, Optional


# ── Supabase (public client for login) ────────────────────────
SUPABASE_URL = "https://qrlnxivfosiludlwnfzr.supabase.co"
SUPABASE_ANON_KEY = (
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
    "eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InFybG54aXZmb3NpbHVkbHduZnpyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjgxOTcyMzcsImV4cCI6MjA4Mzc3MzIzN30."
    "tWpcKM76nYcpGk1UbK133alvVV9_7x2cnZfxubj-xRQ"
)

# ── Credential Storage ────────────────────────────────────────
CONFIG_DIR = Path.home() / ".sigmanticai"
CREDENTIALS_FILE = CONFIG_DIR / "credentials.json"


def save_credentials(data: Dict[str, Any]) -> None:
    """Save credentials to ~/.sigmanticai/credentials.json (mode 600)."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    CREDENTIALS_FILE.write_text(json.dumps(data, indent=2))
    CREDENTIALS_FILE.chmod(stat.S_IRUSR | stat.S_IWUSR)


def load_credentials() -> Optional[Dict[str, Any]]:
    """Load stored credentials, or None if not logged in."""
    if CREDENTIALS_FILE.exists():
        try:
            return json.loads(CREDENTIALS_FILE.read_text())
        except (json.JSONDecodeError, OSError):
            return None
    return None


def clear_credentials() -> None:
    """Remove stored credentials (logout)."""
    if CREDENTIALS_FILE.exists():
        CREDENTIALS_FILE.unlink()

