import json
import pathlib
from config import APP_DIR

CONFIG_PATH = APP_DIR / "global_config.json"

DEFAULT_CONFIG = {
    "ui": {
        "language": "en",
    },
    "network": {
        "mode": "direct",
        "proxy_host": "127.0.0.1",
        "proxy_port": 9050,
        "kill_switch": True
    },

    "files": {
        "seed_dir": str(APP_DIR / "files"),

        "max_seed_mb": 0,
        "downloads_dir": str(APP_DIR / "downloads"),


        "seeding_enabled": True,

        "seed_upload_limit_mbit": 0,
        "cloud_upload_limit_mbit": 0,


        "upload_limit_mbit": 0,
    },

    "cloud": {
        "enabled": False,
        "publish_snapshots": False,
        "publish_files": False,
        "publish_interval_sec": 120,
        "max_snapshot_mb": 64,
        "max_file_mb": 64,
    },
}

def load_global_config():
    if not CONFIG_PATH.exists():
        save_global_config(DEFAULT_CONFIG)
        return DEFAULT_CONFIG

    def _merge(default: dict, cur: dict) -> dict:
        out = dict(cur)
        for k, v in default.items():
            if k not in out:
                out[k] = v
            else:
                if isinstance(v, dict) and isinstance(out.get(k), dict):
                    out[k] = _merge(v, out[k])
        return out

    try:
        with open(CONFIG_PATH, "r") as f:
            loaded = json.load(f)
        if not isinstance(loaded, dict):
            return DEFAULT_CONFIG
        merged = _merge(DEFAULT_CONFIG, loaded)

        if merged != loaded:
            save_global_config(merged)
        return merged
    except Exception:
        return DEFAULT_CONFIG

def save_global_config(config):
    with open(CONFIG_PATH, "w") as f:
        json.dump(config, f, indent=2)
