"""
VelozCLI Configuration

Handles configuration files, credentials storage, and environment settings.
"""

import os
import json
from pathlib import Path
from typing import Optional, Dict, Any
from dotenv import load_dotenv

# Load .env file if it exists
load_dotenv()


def get_config_dir() -> Path:
    """Get CLI configuration directory (~/.veloz)"""
    config_dir = Path.home() / ".veloz"
    config_dir.mkdir(exist_ok=True)
    return config_dir


def get_credentials_path() -> Path:
    """Get path to credentials file"""
    return get_config_dir() / "credentials.json"


def get_config_path() -> Path:
    """Get path to config file"""
    return get_config_dir() / "config.json"


def load_credentials() -> Optional[Dict[str, Any]]:
    """
    Load credentials from file.
    
    Returns:
        dict with token, email, expires, server or None
    """
    creds_path = get_credentials_path()
    
    if not creds_path.exists():
        return None
    
    try:
        with open(creds_path, 'r') as f:
            return json.load(f)
    except (json.JSONDecodeError, IOError):
        return None


def save_credentials(token: str, email: str, expires: int, server: str) -> None:
    """
    Save credentials to file.
    
    Args:
        token: JWT string
        email: User email
        expires: Unix timestamp
        server: Server URL
    """
    creds_path = get_credentials_path()
    
    data = {
        'token': token,
        'email': email,
        'expires': expires,
        'server': server
    }
    
    with open(creds_path, 'w') as f:
        json.dump(data, f, indent=2)
    
    # Set restrictive permissions (Unix only)
    if os.name != 'nt':  # Not Windows
        os.chmod(creds_path, 0o600)


def delete_credentials() -> None:
    """Delete credentials file"""
    creds_path = get_credentials_path()
    if creds_path.exists():
        creds_path.unlink()


def load_config() -> Dict[str, Any]:
    """
    Load config from file.
    
    Returns:
        dict with config values
    """
    config_path = get_config_path()
    
    if not config_path.exists():
        return {}
    
    try:
        with open(config_path, 'r') as f:
            return json.load(f)
    except (json.JSONDecodeError, IOError):
        return {}


def save_config(config: Dict[str, Any]) -> None:
    """Save config to file"""
    config_path = get_config_path()
    
    with open(config_path, 'w') as f:
        json.dump(config, f, indent=2)


def get_connected_cms() -> Optional[str]:
    """Get currently connected CMS"""
    config = load_config()
    return config.get('connected_cms')


def set_connected_cms(cms_name: str, cms_url: str = None) -> None:
    """Set connected CMS"""
    config = load_config()
    config['connected_cms'] = cms_name
    if cms_url:
        config['connected_cms_url'] = cms_url
    save_config(config)


def get_connected_cms_url() -> Optional[str]:
    """Get currently connected CMS URL"""
    config = load_config()
    return config.get('connected_cms_url')


def get_server_url() -> str:
    """
    Get server URL from environment or default.
    
    Checks:
    1. SERVER_TO_CONNECT_TO env var
    2. Credentials file
    3. Default to production
    """
    # Check environment
    env_server = os.environ.get('SERVER_TO_CONNECT_TO')
    if env_server:
        return env_server.rstrip('/')
    
    # Check credentials
    creds = load_credentials()
    if creds and 'server' in creds:
        return creds['server'].rstrip('/')
    
    # Default
    return 'https://veloz.site'


def is_development_mode() -> bool:
    """Check if in development mode"""
    return os.environ.get('DEVELOPMENT', '').lower() == 'true'

