#!/usr/bin/env python3
"""
随机生成护照结果图到 results 目录
"""
import json, sys, random
from datetime import datetime
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from write_lazy_fixed import write_passport_lazy_fixed

FEMALE_SURNAMES = ["EI", "SU", "KHIN", "MAY", "NU", "THAN", "THIDA", "NILAR", "MOE", "YIN"]
FEMALE_GIVEN = ["SU MYAT", "THIN", "ZAR", "THU", "YADANAR", "HTAY", "KHINE", "WAI", "EI", "MON"]
MALE_SURNAMES = ["AUNG", "KYAW", "WIN", "MYINT", "ZAW", "HTET", "TUN", "PHYO", "MIN", "THEIN"]
MALE_GIVEN = ["AUNG", "KYAW", "WIN", "MIN", "HTET", "ZAW", "PHYO", "THEIN", "MYO", "TUN"]
BIRTH_PLACES = ["YANGON", "MANDALAY", "TAUNGGYI", "BAGO", "PATHEIN", "SITTWE", "MYITKYINA", "MAWLAMYINE", "MONYWA", "MEIKTILA", "MATMAN", "KYAINGTONG"]
AUTHORITIES = ["MOHA, KYAINGTONG", "MOHA, YANGON", "MOHA, MANDALAY"]
MONTHS_ABBR = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"]

def fmt_date(dt): return f"{dt.day:02d} {MONTHS_ABBR[dt.month-1]} {dt.year}"

def random_data(sex):
    sex = (sex or random.choice(["M", "F"])).upper()
    if sex == "M":
        surname = random.choice(MALE_SURNAMES)
        given = random.choice(MALE_GIVEN)
    else:
        surname = random.choice(FEMALE_SURNAMES)
        given = random.choice(FEMALE_GIVEN)
    dob = fmt_date(datetime(random.randint(1980, 2005), random.randint(1,12), random.randint(1,28)))
    issue_y = random.randint(2020, 2025)
    issue_m = random.randint(1, 12)
    issue_d = random.randint(1, 28)
    issue = fmt_date(datetime(issue_y, issue_m, issue_d))
    exp_y = min(issue_y + 5, 2035)
    expiry = fmt_date(datetime(exp_y, issue_m, issue_d))
    return {
        "passport_no": "MK" + "".join(str(random.randint(0,9)) for _ in range(6)),
        "sex": sex, "surname": surname, "given_name": given,
        "dob": dob, "birth_place": random.choice(BIRTH_PLACES),
        "issue_date": issue, "expiry_date": expiry,
        "authority": random.choice(AUTHORITIES),
        "nationality": "MYANMAR", "type": "PV", "country_code": "MMR"
    }

if __name__ == "__main__":
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 3
    out_dir = Path("/passport/web/results")
    out_dir.mkdir(exist_ok=True)
    
    template = "/passport/模板/m03.png"
    
    for i in range(n):
        sex = random.choice(["M", "F"])
        data = random_data(sex)
        ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3]
        out_file = out_dir / f"passport_{ts}_{i}.png"
        print(f"Generating {i+1}/{n}: {out_file.name}")
        write_passport_lazy_fixed(template, str(out_file), data, skip_header=False)
    
    print(f"Done! Generated {n} passports in {out_dir}")
