import json
import socket
import hashlib
import uuid
from pathlib import Path

# Stores token at ~/.codedthemes/config.json
CONFIG_DIR = Path.home() / ".codedthemes"
CONFIG_FILE = CONFIG_DIR / "config.json"


def ensure_config_dir():
    """
    Ensures the configuration directory exists.
    """
    CONFIG_DIR.mkdir(exist_ok=True)


def save_config(data: dict):
    """
    Saves the provided configuration data to the config file (merging with existing).
    """
    ensure_config_dir()
    existing = load_config()
    existing.update(data)
    with open(CONFIG_FILE, "w") as f:
        json.dump(existing, f, indent=2)


def get_device_id():
    """
    Returns a unique device ID, stored globally in ~/.codedthemes/device.json.
    """
    device_file = CONFIG_DIR / "device.json"
    
    if device_file.exists():
        try:
            with open(device_file, "r") as f:
                data = json.load(f)
                if data.get("device_id"):
                    return data["device_id"]
        except:
            pass

    # Generate new device ID
    try:
        hostname = socket.gethostname()
        device_uuid = str(uuid.getnode())
        raw_id = f"{hostname}-{device_uuid}"
        device_id = hashlib.sha256(raw_id.encode()).hexdigest()[:12]
    except:
        device_id = str(uuid.uuid4())[:12]
    
    # Save globally (create dir if not exists)
    CONFIG_DIR.mkdir(exist_ok=True)
    try:
        with open(device_file, "w") as f:
            json.dump({"device_id": device_id}, f)
    except:
        pass
        
    return device_id




def load_config():
    """
    Loads the configuration data from the config file.
    """
    if not CONFIG_FILE.exists():
        return {}
    with open(CONFIG_FILE, "r") as f:
        try:
            return json.load(f)
        except json.JSONDecodeError:
            return {}
