#!/usr/bin/env python3
"""NMPA 核心抗肿瘤药种子数据 — 通过 admin API 人工录入

用法：
  python scripts/seed_nmpa_drugs.py

首次运行自动创建所有药品，已存在的按 generic_name 跳过（幂等）。
"""

import os
import sys

import httpx

# ── 配置 ──
API_BASE = os.getenv("API_BASE", "http://localhost:8000/api/v1")
ADMIN_TOKEN = os.getenv("ADMIN_TOKEN", "")

NMPA_DRUGS = [
    # ═══ PD-1 ═══
    {
        "drug_name": "艾瑞卡",
        "generic_name": "Camrelizumab",
        "target": "PD-1",
        "indication": "经典型霍奇金淋巴瘤；肝细胞癌；非小细胞肺癌；食管鳞癌",
        "approval_date": "2019-05-29",
        "source_url": "https://www.nmpa.gov.cn",
    },
    {
        "drug_name": "百泽安",
        "generic_name": "Tislelizumab",
        "target": "PD-1",
        "indication": "经典型霍奇金淋巴瘤；尿路上皮癌；非小细胞肺癌；肝细胞癌；食管鳞癌",
        "approval_date": "2019-12-26",
        "source_url": "https://www.nmpa.gov.cn",
    },
    {
        "drug_name": "达伯舒",
        "generic_name": "Sintilimab",
        "target": "PD-1",
        "indication": "经典型霍奇金淋巴瘤；非小细胞肺癌；肝细胞癌；食管鳞癌；胃癌",
        "approval_date": "2018-12-24",
        "source_url": "https://www.nmpa.gov.cn",
    },
    {
        "drug_name": "安尼可",
        "generic_name": "Penpulimab",
        "target": "PD-1",
        "indication": "经典型霍奇金淋巴瘤；非小细胞肺癌",
        "approval_date": "2021-08-05",
        "source_url": "https://www.nmpa.gov.cn",
    },
    {
        "drug_name": "誉妥",
        "generic_name": "Zimberelimab",
        "target": "PD-1",
        "indication": "经典型霍奇金淋巴瘤",
        "approval_date": "2021-08-30",
        "source_url": "https://www.nmpa.gov.cn",
    },
    {
        "drug_name": "汉斯状",
        "generic_name": "Serplulimab",
        "target": "PD-1",
        "indication": "微卫星高度不稳定(MSI-H)实体瘤；非小细胞肺癌；小细胞肺癌；食管鳞癌",
        "approval_date": "2022-03-24",
        "source_url": "https://www.nmpa.gov.cn",
    },
    {
        "drug_name": "普特利单抗",
        "generic_name": "Pucotenlimab",
        "target": "PD-1",
        "indication": "微卫星高度不稳定(MSI-H)实体瘤",
        "approval_date": "2022-07-19",
        "source_url": "https://www.nmpa.gov.cn",
    },
    # ═══ PD-L1 ═══
    {
        "drug_name": "择捷美",
        "generic_name": "Sugemalimab",
        "target": "PD-L1",
        "indication": "非小细胞肺癌；胃/胃食管结合部腺癌；食管鳞癌",
        "approval_date": "2021-12-20",
        "source_url": "https://www.nmpa.gov.cn",
    },
    {
        "drug_name": "恩沃利单抗",
        "generic_name": "Envafolimab",
        "target": "PD-L1",
        "indication": "微卫星高度不稳定(MSI-H)实体瘤",
        "approval_date": "2021-11-25",
        "source_url": "https://www.nmpa.gov.cn",
    },
    {
        "drug_name": "阿得贝利单抗",
        "generic_name": "Adebrelimab",
        "target": "PD-L1",
        "indication": "小细胞肺癌",
        "approval_date": "2023-02-28",
        "source_url": "https://www.nmpa.gov.cn",
    },
    # ═══ EGFR ═══
    {
        "drug_name": "艾弗沙",
        "generic_name": "Furmonertinib",
        "target": "EGFR",
        "indication": "EGFR T790M 突变非小细胞肺癌",
        "approval_date": "2021-03-03",
        "source_url": "https://www.nmpa.gov.cn",
    },
    {
        "drug_name": "阿美乐",
        "generic_name": "Aumolertinib",
        "target": "EGFR",
        "indication": "EGFR 突变非小细胞肺癌",
        "approval_date": "2020-03-18",
        "source_url": "https://www.nmpa.gov.cn",
    },
    # ═══ ALK ═══
    {
        "drug_name": "贝美纳",
        "generic_name": "Ensartinib",
        "target": "ALK",
        "indication": "ALK 阳性非小细胞肺癌",
        "approval_date": "2020-11-17",
        "source_url": "https://www.nmpa.gov.cn",
    },
    {
        "drug_name": "伊鲁阿克",
        "generic_name": "Iruplinalkib",
        "target": "ALK",
        "indication": "ALK 阳性非小细胞肺癌",
        "approval_date": "2023-06-28",
        "source_url": "https://www.nmpa.gov.cn",
    },
    # ═══ HER2 / ADC ═══
    {
        "drug_name": "爱地希",
        "generic_name": "Disitamab vedotin",
        "target": "HER2",
        "indication": "HER2 阳性胃癌；HER2 阳性尿路上皮癌",
        "approval_date": "2021-06-08",
        "source_url": "https://www.nmpa.gov.cn",
    },
    # ═══ CAR-T ═══
    {
        "drug_name": "奕凯达",
        "generic_name": "Axicabtagene ciloleucel",
        "target": "CD19",
        "indication": "复发/难治性大 B 细胞淋巴瘤",
        "approval_date": "2021-06-23",
        "source_url": "https://www.nmpa.gov.cn",
    },
    {
        "drug_name": "倍诺达",
        "generic_name": "Lisocabtagene maraleucel",
        "target": "CD19",
        "indication": "复发/难治性大 B 细胞淋巴瘤",
        "approval_date": "2022-09-02",
        "source_url": "https://www.nmpa.gov.cn",
    },
]


def main():
    token = ADMIN_TOKEN
    if not token:
        token = input("请输入 admin token: ").strip()

    headers = {"Authorization": f"Bearer {token}"}
    created = 0
    skipped = 0
    errors = []

    # 先查已有 generic_name 列表
    try:
        resp = httpx.get(
            f"{API_BASE}/admin/drug-approvals",
            headers=headers,
            params={"page": 1, "page_size": 200},
            timeout=30,
        )
        resp.raise_for_status()
        exist_generic = {item.get("generic_name", "").lower() for item in resp.json().get("items", [])}
    except Exception as e:
        print(f"⚠️  无法获取现有审批列表，将逐个尝试创建（可能跳过已存在记录）：{e}")
        exist_generic = set()

    for drug in NMPA_DRUGS:
        generic_lower = drug["generic_name"].lower()
        if generic_lower in exist_generic:
            print(f"⏭️  跳过已有: {drug['generic_name']} ({drug['drug_name']})")
            skipped += 1
            continue

        payload = {
            "drug_name": drug["drug_name"],
            "generic_name": drug["generic_name"],
            "target": drug["target"],
            "indication": drug["indication"],
            "approval_agency": "NMPA",
            "approval_type": "new_drug",
            "approval_date": drug["approval_date"],
            "source_url": drug.get("source_url", ""),
        }
        try:
            resp = httpx.post(
                f"{API_BASE}/admin/drug-approvals",
                headers=headers,
                json=payload,
                timeout=30,
            )
            resp.raise_for_status()
            print(f"✅  创建: {drug['drug_name']} ({drug['generic_name']}) → {drug['target']}")
            created += 1
        except Exception as e:
            msg = f"❌  失败: {drug['drug_name']} — {e}"
            print(msg)
            errors.append(msg)

    print(f"\n{'='*50}")
    print(f"创建: {created} | 跳过: {skipped} | 错误: {len(errors)}")
    if errors:
        print(f"错误详情: {errors[0]}")
    return 0 if not errors else 1


if __name__ == "__main__":
    sys.exit(main())
