"""Regional license tiering — per-region pricing & feature differentiation.
Supports: CN (domestic), GLOBAL (international), MENA (Middle East), APAC (Asia-Pacific)."""

from __future__ import annotations
import json, os
from pathlib import Path
from typing import Any, Optional

REGION_TIERS = {
    "CN": {"name": "中国大陆", "currency": "CNY", "price_monthly": 299, "features": ["basic", "advanced", "hermes"]},
    "GLOBAL": {"name": "Global", "currency": "USD", "price_monthly": 49, "features": ["basic", "advanced", "hermes"]},
    "MENA": {"name": "Middle East / North Africa", "currency": "USD", "price_monthly": 39, "features": ["basic", "advanced"]},
    "APAC": {"name": "Asia Pacific", "currency": "USD", "price_monthly": 39, "features": ["basic", "advanced"]},
}

def detect_region() -> str:
    """Detect user's region from environment or geo-IP heuristics."""
    env_region = os.environ.get("GAT_REGION", "")
    if env_region in REGION_TIERS: return env_region
    # Default to GLOBAL for international, CN for domestic
    locale = os.environ.get("LANG", os.environ.get("LC_ALL", ""))
    if any(x in locale.lower() for x in ["zh_cn", "zh-cn", "zhcn"]): return "CN"
    return "GLOBAL"

def get_region_config(region: Optional[str] = None) -> dict[str, Any]:
    """Get pricing and features for a region."""
    r = region or detect_region()
    return REGION_TIERS.get(r, REGION_TIERS["GLOBAL"])

def check_feature_access(region: str, feature: str) -> bool:
    """Check if a feature is available in the given region."""
    cfg = get_region_config(region)
    return feature in cfg.get("features", [])
