"""Credential management for CirtusAI SDK."""

from pathlib import Path
import json


def get_credentials_path() -> Path:
    """Return the path to the credentials file."""
    return Path.home() / ".cirtus" / "credentials.json"


def save_credentials(api_key: str, base_url: str, agent_name: str) -> None:
    """Save credentials to ~/.cirtus/credentials.json."""
    creds_path = get_credentials_path()
    creds_path.parent.mkdir(parents=True, exist_ok=True)
    
    data = {
        "api_key": api_key,
        "base_url": base_url,
        "agent_name": agent_name,
    }
    
    creds_path.write_text(json.dumps(data, indent=2))
    creds_path.chmod(0o600)  # Read/write for owner only


def load_credentials() -> dict | None:
    """Load credentials from ~/.cirtus/credentials.json."""
    creds_path = get_credentials_path()
    
    if not creds_path.exists():
        return None
    
    try:
        return json.loads(creds_path.read_text())
    except (json.JSONDecodeError, OSError):
        return None


def clear_credentials() -> None:
    """Remove the credentials file."""
    creds_path = get_credentials_path()
    
    if creds_path.exists():
        creds_path.unlink()
