"""Configuration for the TaskingTech Desktop Agent."""

import os
import json
import platform
import uuid

CONFIG_DIR = os.path.join(os.path.expanduser("~"), ".tasking-desktop")
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")

DEFAULT_CONFIG = {
    "server_url": "https://tasking.tech",
    "api_key": "",
    "agent_id": "",
    "poll_interval": 1.5,
    "heartbeat_interval": 15,
}


def get_os_info():
    """Get cross-platform OS information."""
    return {
        "platform": platform.system().lower(),  # linux, darwin, windows
        "version": platform.version(),
        "release": platform.release(),
        "machine": platform.machine(),
        "hostname": platform.node(),
    }


def load_config():
    """Load config from ~/.tasking-desktop/config.json, create if missing."""
    os.makedirs(CONFIG_DIR, exist_ok=True)

    if os.path.exists(CONFIG_FILE):
        with open(CONFIG_FILE, "r") as f:
            config = json.load(f)
        # Merge with defaults for any missing keys
        for k, v in DEFAULT_CONFIG.items():
            if k not in config:
                config[k] = v
        return config

    # Create default config with unique agent_id
    config = {**DEFAULT_CONFIG, "agent_id": str(uuid.uuid4())}
    save_config(config)
    return config


def save_config(config):
    """Save config to disk."""
    os.makedirs(CONFIG_DIR, exist_ok=True)
    with open(CONFIG_FILE, "w") as f:
        json.dump(config, f, indent=2)


def set_api_key(key):
    """Set the API key in config."""
    config = load_config()
    config["api_key"] = key
    save_config(config)
    return config
