from __future__ import annotations

import json
import os
import shutil
from datetime import datetime, timezone
from pathlib import Path


root = Path("/opt/charter-live/live_deploy_v2")
policy_path = root / "v2_stats_trade_policy.json"
backup_dir = Path("/opt/charter-live/backups/alert_semantic_celo_verified_20260902")
close_order_id = "699f792f-fe80-4b65-ab67-465fa8656a8b"

policy = json.loads(policy_path.read_text(encoding="utf-8"))
bucket = policy.setdefault("operational_excluded_closed_order_ids", {})
# Remove only the erroneous entry-id rule previously added for this incident.
wrong_id = "463ba091-43b4-45db-9194-a6c73c6e7219"
if bucket.get(wrong_id, {}).get("request_id") == "41f9f505-779c-4a7c-8366-23edba3199d0":
    bucket.pop(wrong_id)
bucket[close_order_id] = {
    "reason": "TV_PARTIAL_EXIT_INTERPRETED_AS_FULL_SIZED_ENTRY",
    "proposal_id": "operator-20260902-celo-semantic-protocol-error",
    "approved_by": "Mattia",
    "approved_at": datetime.now(timezone.utc).isoformat(),
    "request_id": "41f9f505-779c-4a7c-8366-23edba3199d0",
    "entry_order_id": wrong_id,
    "requested_qty": 2022.926,
    "executed_qty": 19920.2,
}

backup_dir.mkdir(parents=True, exist_ok=True)
backup = backup_dir / "v2_stats_trade_policy.json.before"
if not backup.exists():
    shutil.copy2(policy_path, backup)

candidate = policy_path.with_suffix(".json.new")
candidate.write_text(json.dumps(policy, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
json.loads(candidate.read_text(encoding="utf-8"))
os.replace(candidate, policy_path)
print(json.dumps({"excluded": close_order_id, "backup": str(backup)}))
