from __future__ import annotations

import json
import os
from typing import Any, Dict


def _policy_store_from_env() -> Dict[str, Any]:
    """
    Optional env override for demo policy store.
    Expected JSON shape:
    {
      "refund_policy:v1": {
        "clauses": [
          {"id":"dup_charge_refund", "title":"Duplicate Charge Refund", "rule":"..."}
        ]
      }
    }
    """
    raw = os.getenv("REFUND_POLICY_STORE_JSON", "").strip()
    if not raw:
        return {}
    try:
        loaded = json.loads(raw)
    except Exception:
        return {}
    return loaded if isinstance(loaded, dict) else {}


def fetch_policy_snapshot(*, policy_version: str = "") -> Dict[str, Any]:
    """
    Returns a versioned policy snapshot for the policy interpreter subagent.
    """
    effective_policy_version = str(policy_version or os.getenv("REFUND_POLICY_VERSION", "refund_policy:v1")).strip() or "refund_policy:v1"
    store = _policy_store_from_env()
    default_policy = {
        "policy_version": effective_policy_version,
        "clauses": [
            {
                "id": "dup_charge_refund",
                "title": "Duplicate Charge Refund",
                "rule": "If duplicate succeeded charges are detected for the same amount and merchant window, refund one charge.",
            },
            {
                "id": "restock_flag_gate",
                "title": "Restock Eligibility Gate",
                "rule": "If pricing flags indicate restockEligible=false for return-based refund flows, escalate or deny per policy.",
            },
        ],
    }
    env_row = store.get(effective_policy_version, {})
    if isinstance(env_row, dict):
        merged = dict(default_policy)
        merged.update(env_row)
        merged["policy_version"] = str(merged.get("policy_version") or effective_policy_version)
        return merged
    return default_policy
