#!/usr/bin/env python3
"""
Configuration utilities for Abflug clients.

Provides functions to load API keys and server URLs from butter.json or abflug.json if available.
"""

import hashlib
import json
import os
import sys
from typing import Optional

# Default server URL if not found in config files
DEFAULT_SERVER_URL = "https://abflug.cloud"


def _get_base_dir() -> str:
    """
    Determine the directory where config files should be loaded from.
    Works for:
    - normal Python execution (macOS, Linux, Windows)
    - PyInstaller onefile executables (Windows .exe)
    """
    if getattr(sys, 'frozen', False):
        # Running as PyInstaller EXE
        return os.path.dirname(sys.executable)
    else:
        # Running as normal Python script
        return os.path.dirname(os.path.abspath(__file__))


def _load_config_file(filename: str) -> Optional[dict]:
    """
    Load a JSON config file from the appropriate directory.
    """
    base_dir = _get_base_dir()
    config_path = os.path.join(base_dir, filename)

    if not os.path.exists(config_path):
        return None

    try:
        with open(config_path, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return None


def get_butter_api_key() -> Optional[str]:
    for config_file in ["butter.json", "abflug.json"]:
        config = _load_config_file(config_file)
        if config:
            api_key = config.get("api_key", "").strip()
            if api_key:
                return api_key
    return None


def get_debug_api_requests() -> bool:
    for config_file in ["butter.json", "abflug.json"]:
        config = _load_config_file(config_file)
        if config:
            value = config.get("debug_api_requests", "False")
            if isinstance(value, bool):
                return value
            if isinstance(value, str):
                return value.lower() == "true"
    return False


def compute_own_icao(api_key: str) -> Optional[str]:
    """
    Compute own ICAO address from API key (same method as server uses).
    Used to identify own aircraft in traffic API responses.
    Must stay in sync with server implementation.
    """
    if not api_key or not api_key.strip():
        return None
    hash_obj = hashlib.md5(api_key.encode())
    return hash_obj.hexdigest()[:6].upper()


def get_server_url() -> str:
    for config_file in ["butter.json", "abflug.json"]:
        config = _load_config_file(config_file)
        if config:
            server_url = config.get("server", "").strip()
            if server_url:
                return server_url
    return DEFAULT_SERVER_URL
