"""
ZeroShot SDK - API Key management.

Stores credentials in ~/.zeroshot/config.toml
"""

import os
from pathlib import Path
from typing import Optional

try:
    import toml
except ImportError:
    toml = None


CONFIG_DIR = Path.home() / ".zeroshot"
CONFIG_FILE = CONFIG_DIR / "config.toml"


def get_config_path() -> Path:
    """Get the config file path."""
    return CONFIG_FILE


def ensure_config_dir():
    """Ensure the config directory exists."""
    CONFIG_DIR.mkdir(exist_ok=True)


def load_config() -> dict:
    """Load configuration from file."""
    if not CONFIG_FILE.exists():
        return {}
    
    if toml is None:
        # Fallback: simple key=value parsing
        config = {}
        with open(CONFIG_FILE) as f:
            for line in f:
                line = line.strip()
                if "=" in line and not line.startswith("#"):
                    key, value = line.split("=", 1)
                    config[key.strip()] = value.strip().strip('"')
        return config
    
    with open(CONFIG_FILE) as f:
        return toml.load(f)


def save_config(config: dict):
    """Save configuration to file."""
    ensure_config_dir()
    
    if toml is None:
        # Fallback: simple key=value format
        with open(CONFIG_FILE, "w") as f:
            for key, value in config.items():
                f.write(f'{key} = "{value}"\n')
    else:
        with open(CONFIG_FILE, "w") as f:
            toml.dump(config, f)


def get_api_key() -> Optional[str]:
    """
    Get the stored API key.
    
    Checks:
    1. ZEROSHOT_API_KEY environment variable
    2. ~/.zeroshot/config.toml
    
    Returns:
        API key string or None if not found
    """
    # Check environment variable first
    env_key = os.environ.get("ZEROSHOT_API_KEY")
    if env_key:
        return env_key
    
    # Check config file
    config = load_config()
    return config.get("api_key")


def save_api_key(api_key: str):
    """
    Save API key to config file.
    
    Args:
        api_key: The API key to save (zsk_...)
    """
    config = load_config()
    config["api_key"] = api_key
    save_config(config)


def get_api_url() -> str:
    """
    Get the API base URL.
    
    Checks:
    1. ZEROSHOT_API_URL environment variable
    2. ~/.zeroshot/config.toml
    3. Default: https://api.0eroshot.com
    """
    # Check environment variable
    env_url = os.environ.get("ZEROSHOT_API_URL")
    if env_url:
        return env_url
    
    # Check config file
    config = load_config()
    return config.get("api_url", "https://api.0eroshot.com")


def save_api_url(api_url: str):
    """Save API URL to config file."""
    config = load_config()
    config["api_url"] = api_url
    save_config(config)


def clear_config():
    """Clear all stored configuration."""
    if CONFIG_FILE.exists():
        CONFIG_FILE.unlink()
