#!/usr/bin/env python3
"""筛选导入失败行（站名未匹配 / 加氢量为空），并按规则生成「修正后加氢站名称」。"""

from __future__ import annotations

import argparse
from pathlib import Path

import pandas as pd

# 原名称 -> 导入系统应使用的站点名称
STATION_RENAME: dict[str, str] = {
    "张家港港城加氢站": "江苏嘉化氢能港城加氢站",
    "重庆销售渝中分公司丝路加油站": "重庆丝路加氢站",
    "武汉双龙站": "武汉中石化双龙站",
    "皖能集团龙塘综合能源港": "皖能集团龙塘综合能源港(CNG、H2、充换电)",
    "上海嘉氢实业加氢站（江桥重塑）": "上海嘉氢实业加氢站（江桥重塑）-暂停营业",
    "如皋神华加氢站": "神华加氢站",
    "宁波慈溪加氢站": "国家电投宁波慈溪加氢站",
    "江苏花桥开发区加氢站": "昆山市中国石油昆山花桥加油站(花安路北50米)",
    "江南西彭综合能源站": "中国石化江南西彭综合能源站",
    "江南半山环道加能站": "中国石化江南半山环道加能站",
    "海德利森（丹灶）加氢站": "丹灶海德利森加氢站",
    "广州开泰北加油站": "中国石化广州开泰北加油加氢站",
    "广州金坑加油站": "中国石化广州金坑加氢站",
    "广东中恒东明三路油站": "东明三路综合能源站",
    "诚志AP银河路加氢站": "诚志空气产品银河路加氢站",
    "成都天府机场高速南站(含网点)": "成都天府机场高速南站",
    "成都天府机场高速北站(含网点)": "成都天府机场高速北站",
}


def _fix_station_name(val) -> str:
    if pd.isna(val):
        return ""
    s = str(val).strip()
    return STATION_RENAME.get(s, s)


def process(in_path: Path, out_path: Path, sheet: str = "失败记录") -> None:
    df = pd.read_excel(in_path, sheet_name=sheet)
    reason = df["导入错误原因"].astype(str)
    mask_nomatch = reason.str.startswith("加氢站名称未匹配到站点")
    mask_empty_qty = reason == "加氢量为空"
    mask_union = mask_nomatch | mask_empty_qty

    df_nomatch = df.loc[mask_nomatch].copy()
    df_empty_qty = df.loc[mask_empty_qty].copy()
    merged = df.loc[mask_union].copy()
    reasons: list[str] = []
    for idx in merged.index:
        parts: list[str] = []
        if bool(mask_nomatch.loc[idx]):
            parts.append("加氢站名称未匹配到站点")
        if bool(mask_empty_qty.loc[idx]):
            parts.append("加氢量为空")
        reasons.append("；".join(parts))
    merged["筛选原因"] = reasons

    for frame in (df_nomatch, df_empty_qty, merged):
        frame["修正后加氢站名称"] = frame["加氢站名称"].map(_fix_station_name)

    keys = set(STATION_RENAME.keys())
    nm = df_nomatch["加氢站名称"].map(lambda x: str(x).strip() if pd.notna(x) else "")
    unmapped_mask = ~nm.isin(keys) & (nm != "")
    unmapped = (
        df_nomatch.loc[unmapped_mask, ["加氢站名称", "订单编号", "加氢时间", "车牌", "导入错误原因"]]
        .drop_duplicates(subset=["加氢站名称"])
        .sort_values("加氢站名称")
    )

    with pd.ExcelWriter(out_path, engine="openpyxl") as w:
        df_nomatch.to_excel(w, sheet_name="未匹配站点", index=False)
        df_empty_qty.to_excel(w, sheet_name="加氢量为空", index=False)
        merged.to_excel(w, sheet_name="合并_含筛选原因", index=False)
        unmapped.to_excel(w, sheet_name="未匹配_无映射规则", index=False)

    print(f"已写出: {out_path}")
    print(f"  未匹配站点: {len(df_nomatch)} 行")
    print(f"  加氢量为空: {len(df_empty_qty)} 行")
    print(f"  合并: {len(merged)} 行")
    print(f"  未匹配中尚无重命名规则的站名种类: {len(unmapped)}（见工作表「未匹配_无映射规则」）")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("input_xlsx", type=Path)
    ap.add_argument("-o", "--out", type=Path, required=True)
    ap.add_argument("--sheet", default="失败记录")
    args = ap.parse_args()
    process(args.input_xlsx.resolve(), args.out.resolve(), sheet=args.sheet)


if __name__ == "__main__":
    main()
