import json
import os
import stat

CONFIG_PATH = os.path.expanduser("~/.gizerbridge_config.json")
SENT_PATH = os.path.expanduser("~/.gizerbridge_sent.json")

DEFAULT_INSTRUMENTS = {
    "MNQ": {"tick_size": 0.25, "tick_value": 0.50,  "enabled": True},
    "NQ":  {"tick_size": 0.25, "tick_value": 5.00,  "enabled": False},
    "ES":  {"tick_size": 0.25, "tick_value": 12.50, "enabled": False},
    "MES": {"tick_size": 0.25, "tick_value": 1.25,  "enabled": False},
}

DEFAULT_CONFIG = {
    "api_key":   "",
    "email":     "",
    "dtc_host":  "localhost",
    "dtc_port":  11099,
    "accounts":  [],
    "instruments": DEFAULT_INSTRUMENTS,
}


def load_config():
    if not os.path.exists(CONFIG_PATH):
        return dict(DEFAULT_CONFIG)
    with open(CONFIG_PATH, encoding="utf-8") as f:
        cfg = json.load(f)
    # Merge missing instrument defaults
    for name, defaults in DEFAULT_INSTRUMENTS.items():
        cfg.setdefault("instruments", {}).setdefault(name, defaults)
    return cfg


def save_config(cfg):
    with open(CONFIG_PATH, "w", encoding="utf-8") as f:
        json.dump(cfg, f, indent=2, ensure_ascii=False)
    os.chmod(CONFIG_PATH, stat.S_IRUSR | stat.S_IWUSR)


def load_sent():
    if not os.path.exists(SENT_PATH):
        return set()
    with open(SENT_PATH, encoding="utf-8") as f:
        return set(json.load(f))


def save_sent(sent_set):
    with open(SENT_PATH, "w", encoding="utf-8") as f:
        json.dump(list(sent_set), f)
