#!/usr/bin/env python3
"""取四个血清型的登革热参考多蛋白序列 + UniProt 自带的链段坐标（prM / E 等）。

坐标一律取自 UniProt 注释，不硬编码 —— 硬编码的坐标改一版就错，且没人能核。
"""
import json, urllib.parse, urllib.request

REF = {"DENV-1": "P27909", "DENV-2": "P29990", "DENV-3": "Q6YMS4", "DENV-4": "Q2YHF0"}
API = "https://rest.uniprot.org/uniprotkb"


def get(acc):
    url = f"{API}/{acc}.json"
    with urllib.request.urlopen(url, timeout=120) as fh:
        return json.load(fh)


out = {}
for name, acc in REF.items():
    try:
        d = get(acc)
    except Exception as e:
        print(f"  ⚠️ {name} {acc} 取不到: {str(e)[:50]}")
        continue
    seq = d["sequence"]["value"]
    chains = {}
    for f in d.get("features", []):
        if f.get("type") in ("Chain", "Peptide"):
            nm = f.get("description", "")
            loc = f["location"]
            s, e = loc["start"].get("value"), loc["end"].get("value")
            if s and e:
                chains[nm] = [s, e]
    out[name] = {"accession": acc, "length": len(seq), "sequence": seq, "chains": chains,
                 "organism": d.get("organism", {}).get("scientificName", "")}
    print(f"  {name} {acc}  长度 {len(seq)}  链段 {len(chains)} 个: {list(chains)[:5]}")
json.dump(out, open("sequences.json", "w"), ensure_ascii=False)
print(f"  → sequences.json（{len(out)}/4 个血清型）")
