"""Canonical forms for the restored flood calculators; no new parameter tables."""

from __future__ import annotations

from typing import Any

from . import core


TIEYUAN_RESULT_COLUMNS = [
    "设计频率", "点面折减系数η", "面平均暴雨参数S（mm/h）", "产流因子k1",
    "损失因子k2", "主河槽汇流因子K1", "山坡汇流因子K2", "山坡与主河槽综合汇流因子X",
    "K1/K2", "流域汇流特征指数y", "K1+K2", "γ", "径流系数ψ(C)",
    "暴雨衰减指数n", "n`", "Cn", "同时汇流的时间系数P1", "同时汇流面积系数P", "洪峰流量（m3/s）",
]


def _field(key: str, label: str, default: Any = "", unit: str = "", **extra: Any) -> dict[str, Any]:
    return {"key": key, "label": label, "default": default, "unit": unit,
            "type": "number", "required": False, "help": "", **extra}


def _select(key: str, label: str, default: str, choices: list[tuple[str, str]], **extra: Any) -> dict[str, Any]:
    return _field(key, label, default, type="select",
                  options=[{"value": value, "label": text} for value, text in choices], **extra)


def program_input_schema(program_id: str) -> dict[str, Any] | None:
    if program_id == "1-01":
        fields = [
            _field("area_km2", "流域面积", 47.02, "km²", required=True),
            _field("frequencies", "计算重现期", "100,50,20,10", "年", type="text",
                   help="保留重现期键；100年对应设计频率1%。"),
        ]
        for duration, mean, cv in (("1h", 38.5, 0.45), ("6h", 64.0, 0.5), ("24h", 95.0, 0.55)):
            prefix = "h" + duration[:-1]
            fields.extend([
                _field(f"{prefix}_mean_mm", f"{duration} 点雨量均值", mean, "mm", required=True),
                _field(f"{prefix}_cv", f"{duration} 点雨量变差系数 Cv", cv),
            ])
        fields.append(_field("cs_ratio", "偏态系数比值 Cs/Cv", 3.5))
        for duration in (1, 3, 6, 24):
            fields.extend([
                _field(f"alpha{duration}", f"{duration}h 点面折减系数 α", 1.0),
                _field(f"gamma{duration}", f"{duration}h 流域形状修正系数 γ", 1.0),
            ])
    elif program_id == "1-02":
        fields = [
            _field("basin_name", "流域名称", "示例流域", type="text"),
            _field("area", "流域面积 F", 47.02, "km²", required=True),
            _field("river_length_l1", "主河道长度 L1", 13.8, "km", required=True),
            _field("river_slope_j1", "主河道比降 J1", 0.095724, "小数", required=True,
                   help="沿用原桥接数值口径，1‰填0.001；不对旧草稿自动换算。"),
            _field("slope_length_l2", "坡面长度 L2", unit="km", help="留空沿用历史估算式 L2=F/(2.7L1)。"),
            _field("slope_slope_i2", "山坡平均坡度 J2（I2）", unit="小数", help="留空沿用历史估算式 J2=0.6J1。"),
            _field("a1", "主河槽汇流参数 A1", 0.341, help="仅为历史软件可调默认值，不是土类规范表；按项目依据核定。"),
            _field("a2", "山坡汇流参数 A2", 0.025, help="仅为历史软件可调默认值；用户新参数表尚未提供。"),
            _field("n", "暴雨衰减指数 n", 0.65),
            _select("soil_class", "土类", "III", [(key, f"{key}类土") for key in core.TIE_SOIL_CLASS_PARAMS]),
            _select("moisture_condition", "前期土壤水分", "medium", [("wet", "湿润"), ("medium", "中等"), ("dry", "干燥")]),
            _select("c_landform", "地貌", "高低山", [(key, key) for key in ("高低山", "丘陵", "平坦")]),
            _select("soil_param_mode", "产流损失参数来源", "legacy", [
                ("legacy", "土类查表（已有人工值优先）"), ("table", "按土类及前期水分查表"), ("manual", "人工输入 R、r1")
            ], help="查表仅使用已有 TIE_SOIL_CLASS_PARAMS，不含 A1/A2 参数表。"),
            _field("r_param", "损失参数 R", visibleWhen={"soil_param_mode": ["legacy", "manual"]},
                   help="兼容模式留空按土类查表；人工模式必须填写。"),
            _field("r1_param", "损失指数 r1", visibleWhen={"soil_param_mode": ["legacy", "manual"]},
                   help="兼容模式留空按前期水分查表；人工模式必须填写。"),
            _select("runoff_coefficient_auto", "径流系数 C 取值方式", "false", [
                ("false", "人工输入"), ("true", "按表3-3自动查算")
            ], help="自动值由土类、前期水分、地貌、面积、n、S逐频率确定。"),
            _field("runoff_coefficient", "径流系数 C", 0.86,
                   visibleWhen={"runoff_coefficient_auto": ["false"]}),
            _select("rainfall_mode", "24h 暴雨输入方式", "direct", [
                ("direct", "直接输入各重现期面雨量"), ("statistics", "由点雨量均值、Cv、Cs/Cv计算")
            ]),
        ]
        for key, label, default, unit in (
            ("h24_mean", "24h 点雨量均值", 70, "mm"),
            ("h24_cv", "24h 点雨量变差系数 Cv", 0.47, ""),
            ("h24_cs_ratio", "24h 偏态系数比值 Cs/Cv", 3.5, ""),
            ("areal_reduction", "点面折减系数 η", 1.0, ""),
            ("shape_correction", "流域形状修正系数 φ", 1.0, ""),
        ):
            fields.append(_field(key, label, default, unit, required=True,
                                 visibleWhen={"rainfall_mode": ["statistics"]}))
        defaults = {"100": 180, "50": 160, "20": 135, "10": 118}
        for freq in core.TIE_FREQUENCIES:
            probability = core.TIE_FREQUENCY_PROBABILITIES[freq]
            fields.append(_field(f"h24_{freq}", f"24h 面雨量（{freq}年，P={probability:.4g}%）",
                                 defaults.get(freq, ""), "mm", visibleWhen={"rainfall_mode": ["direct"]},
                                 help="已经是面雨量，不再乘点面折减或形状修正；留空不计算该频率。"))
        fields.append(_field("beta1", "历史兼容参数 β1", 0.65,
                             help="旧参数键保留归档；现有 core 铁一院洪峰公式未使用该值，不改变计算结果。"))
    elif program_id == "1-03":
        fields = [
            _field("basin_name", "流域名称", "示例流域", type="text"),
            _field("area", "流域面积 F", 47.02, "km²", required=True),
            _select("region_id", "地区经验分区", "", [("", "请选择地区经验分区")] + [
                (str(region.region_id), region.name) for region in core.REGION_PARAMS
            ], required=True, help="按水系与适用面积明确选择，不自动猜测或截断分区编号。"),
            _select("allow_out_of_range", "分区面积范围校核", "false", [
                ("false", "严格校核（不允许外推）"), ("true", "允许外推（结果保留警告）")
            ]),
        ]
    else:
        return None
    return {"program_id": program_id, "fields": fields}
