"""高级运费规则：随代码发布的内置模板（只读）。

这些是**带版本号的代码模板**，不是前端常量：模板的形状必须跟着 conditions/pricing 契约一起演进，
放前端会在契约变更时静默过期。对外只读——不提供全局超管 CRUD 面。
租户用模板 = 复制一份出来改，模板本身永远不被修改。
"""
from copy import deepcopy
from types import MappingProxyType

#: 模板结构变更时 +1，方便排查"这条规则当年是从哪版模板起草的"。
TEMPLATE_VERSION = 1


def _tpl(key, name_en, name_zh, conditions, pricing, delivery_mode="standard"):
    return {
        "key": key,
        "version": TEMPLATE_VERSION,
        "delivery_mode": delivery_mode,
        "presentation": {"name": {"en-NZ": name_en, "zh-CN": name_zh}},
        "conditions": conditions,
        "pricing": pricing,
    }


_TEMPLATES = {
    t["key"]: t for t in (
        _tpl("pickup_only", "Store Pickup", "到店自提",
             {"delivery_mode": ["pickup"]},
             {"mode": "flat", "amount": "0", "free_shipping": True},
             delivery_mode="pickup"),

        _tpl("zone_delivery", "Zone Delivery", "按区域配送",
             {"country": {"include": ["NZ"]}, "province": {"include": ["Auckland"]}},
             {"mode": "flat", "amount": "8.50"}),

        _tpl("free_over_amount", "Free Over Amount", "满额免运费",
             {"subtotal": {"min": 100}},
             {"mode": "flat", "amount": "0", "free_shipping": True}),

        _tpl("weight_tier", "Weight Tiers", "按重量阶梯",
             {},
             {"mode": "tiered_weight", "calculation": "single", "tiers": [
                 {"start": 0, "end": 5, "amount": "8.00"},
                 {"start": 5, "end": 10, "amount": "14.00"},
                 {"start": 10, "end": None, "amount": "3.00", "block": 5},
             ]}),

        _tpl("dimensional_weight", "Dimensional Weight", "按体积重",
             {},
             {"mode": "tiered_dimensional_weight", "dimensional_divisor": 5000, "tiers": [
                 {"start": 0, "end": 10, "amount": "12.00"},
                 {"start": 10, "end": None, "amount": "1.50", "proportional": True},
             ]}),

        # inherit 的 fee 已含核心 ShippingSurcharge，这里只叠一笔偏远地区附加费，
        # 千万不要再把同一笔附加费建成 sum 聚合的成员（会重复收）。
        _tpl("postcode_surcharge", "Rural Postcode Surcharge", "偏远邮编附加费",
             {"postcode_patterns": {"include": ["9*"]}},
             {"mode": "inherit", "modifier": {"add": "6.00"}}),

        _tpl("custom", "Custom Rule", "自定义规则",
             {},
             {"mode": "flat", "amount": "0"}),
    )
}

TEMPLATES = MappingProxyType(_TEMPLATES)


def list_templates() -> tuple[str, ...]:
    return tuple(_TEMPLATES)


def get_template(key: str) -> dict:
    """返回深拷贝：调用方随便改，改不到模板本体。"""
    if key not in _TEMPLATES:
        raise ValueError(f"未知模板: {key}")
    return deepcopy(_TEMPLATES[key])


__all__ = ["TEMPLATES", "TEMPLATE_VERSION", "get_template", "list_templates"]
