"""Align NinjaTrader addon config (webhook secret) with the local Safeguard server."""

from __future__ import annotations

import json
from pathlib import Path

from config import settings


def ninja_custom_dir() -> Path | None:
    home = Path.home()
    custom = home / "Documents" / "NinjaTrader 8" / "bin" / "Custom"
    if custom.is_dir():
        return custom
    return None


def sync_ninja_addon_config() -> Path | None:
    """
    Write / update Documents\\NinjaTrader 8\\bin\\Custom\\PaychekSafeguard.json
    so the addon webhook_secret matches the running Safeguard server.
    """
    custom = ninja_custom_dir()
    if custom is None:
        return None

    path = custom / "PaychekSafeguard.json"
    data: dict = {}
    if path.is_file():
        try:
            loaded = json.loads(path.read_text(encoding="utf-8"))
            if isinstance(loaded, dict):
                data = loaded
        except Exception:
            data = {}

    data["safeguard_url"] = f"http://127.0.0.1:{int(settings.port)}"
    data["webhook_secret"] = settings.webhook_secret
    data.setdefault("block_rejected_orders", True)
    data.setdefault("auto_flatten_max_risk", True)
    data.setdefault("max_risk_usd", 50)
    data.setdefault("show_status_on_start", True)
    data.setdefault("always_on_top", True)

    path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
    return path
