# -*- coding: utf-8 -*-
# Round 194 batch add: 5 programs
import os, re

ROOT = r"D:\work buddy\2026-11-05-14-15-52"
IDX = os.path.join(ROOT, "index_main.html")

PROGRAMS = [
    {
        "id": "nyu-animal-studies-ma",
        "s": "nyu",
        "n": "动物研究文学硕士",
        "en": "MA in Animal Studies",
        "deg": "MA",
        "lvl": "m",
        "stem": 0,
        "dur": "1 year full-time",
        "ddl": "Feb 15 (Fall priority, rolling after)",
        "lang": "TOEFL/IELTS required for non-native speakers (GSAS standard)",
        "test": '{"cls":"GRE not required - do not send scores; will not be reviewed"}',
        "tui": "Refer to GSAS tuition schedule (待补 exact figure)",
        "url": "details/nyu-animal-studies-ma.html",
        "school": "New York University",
        "school_en": "New York University",
        "school_short": "NYU",
        "college": "Graduate School of Arts and Science (GSAS), Department of Environmental Studies",
        "intro": "Interdisciplinary MA drawing from humanities, social sciences, and natural sciences to examine human-animal relationships, ethics, and ecological significance. Housed in Environmental Studies; launched 2010.",
        "curriculum": "Personalized course of study; core seminars in animal ethics, human-animal studies, environmental humanities; MA thesis or capstone project (待补 exact credit count)",
        "career": "PhD preparation, animal advocacy organizations, policy, museum/sanctuary work, education",
        "requirements": "BA/BS any field; Statement of Academic Purpose (max 2 double-spaced pages); academic writing sample (max 25 pages, English); optional second work sample; TOEFL/IELTS unless exempt",
        "website": "https://as.nyu.edu/departments/environment/Graduate.html",
    },
    {
        "id": "col-qmss-ma",
        "s": "col",
        "n": "社会科学量化方法文学硕士",
        "en": "MA in Quantitative Methods in the Social Sciences (QMSS)",
        "deg": "MA",
        "lvl": "m",
        "stem": 1,
        "dur": "1-2 years full-time / part-time",
        "ddl": "Jan 14, 2027 (Fall 2027)",
        "lang": "TOEFL/IELTS/Duolingo required (GSAS standard)",
        "test": '{"cls":"GRE/GMAT optional during current cycle; submitted scores will be evaluated"}',
        "tui": "Refer to GSAS tuition schedule (待补 exact figure)",
        "url": "details/col-qmss-ma.html",
        "school": "Columbia University",
        "school_en": "Columbia University",
        "school_short": "Columbia",
        "college": "Graduate School of Arts and Science (GSAS)",
        "intro": "Interdisciplinary MA bridging quantitative methods (statistics, programming, data science) and social science substance. About half of each cohort is international; many students enter after several years of post-baccalaureate work.",
        "curriculum": "Core statistics, research design, programming, regression, causal inference, electives across social sciences; MA capstone or thesis (待补 exact credit count)",
        "career": "Applied research, data analysis in policy/government/nonprofit/tech, PhD preparation in social sciences",
        "requirements": "BA/BS any major with quantitative coursework; Statement of Academic Purpose; Personal Statement (max 1000 words); 3 letters of recommendation (at least 2 academic); resume/CV; no writing sample required",
        "website": "https://qmss.columbia.edu/",
    },
    {
        "id": "up-melc-mes-ma",
        "s": "up",
        "n": "中东语言文明·美索不达米亚文学硕士",
        "en": "MA in Middle Eastern Languages and Cultures: Mesopotamian Civilization",
        "deg": "MA",
        "lvl": "m",
        "stem": 0,
        "dur": "3 semesters full-time",
        "ddl": "Dec 8, 2026, 11:59 PM EST (Fall 2027)",
        "lang": "TOEFL/IELTS required (SAS standard)",
        "test": '{"cls":"GRE not listed as required for MELC MA"}',
        "tui": "Refer to SAS tuition schedule (待补 exact figure)",
        "url": "details/up-melc-mes-ma.html",
        "school": "University of Pennsylvania",
        "school_en": "University of Pennsylvania",
        "school_short": "Penn",
        "college": "School of Arts and Sciences (SAS), Department of Near Eastern Languages and Civilizations (NELC/MELC)",
        "intro": "Independent terminal MA (not PhD-route) in Mesopotamian Civilizations: advanced study of Sumerian/Akkadian philology, ancient Near Eastern history and archaeology. One of MELC's five MA fields alongside Biblical Studies, Egyptology, Hebrew & Judaic Studies, and Middle Eastern Literatures & Societies.",
        "curriculum": "Minimum 12 course units; reading proficiency exam in one modern research language (e.g., French/German); MA Final Exams (up to 4, at least 1 language exam); thesis OR two research papers",
        "career": "PhD preparation in Assyriology/Near Eastern studies, museum/curation, academia, cultural heritage; not a guarantee of MELC PhD admission",
        "requirements": "Relevant undergraduate preparation (introductory ancient languages, literature, history, religion); provisional admission possible for students lacking background (provisional courses at student's expense); application fee USD 90; fee waivers available",
        "website": "https://nelc.sas.upenn.edu/graduate/general-maprocedures",
    },
    {
        "id": "nyu-hsb-ma",
        "s": "nyu",
        "n": "人体骨骼生物学文学硕士",
        "en": "MA/MS in Human Skeletal Biology",
        "deg": "MA",
        "lvl": "m",
        "stem": 0,
        "dur": "1-2 years full-time",
        "ddl": "Feb 1 (Fall admission)",
        "lang": "TOEFL/IELTS required unless exempt (native speaker, US PR, or English-medium degree)",
        "test": '{"cls":"GRE not required - do not send scores; will not be reviewed"}',
        "tui": "Refer to GSAS tuition schedule (待补 exact figure)",
        "url": "details/nyu-hsb-ma.html",
        "school": "New York University",
        "school_en": "New York University",
        "school_short": "NYU",
        "college": "Graduate School of Arts and Science (GSAS), Department of Anthropology",
        "intro": "Terminal MA in biological anthropology / skeletal biology training for forensic science careers (medical examiner, coroner, armed forces, law enforcement, mass disaster response) and as preparation for PhD work in skeletal biology, molecular anthropology, human evolution.",
        "curriculum": "36 points total; required Departmental Seminar ANTH-GA 1000; core Human Osteology (1516), Interpreting Human Skeletal Morphology (1520), Biological Variation Among Human Populations (1517) OR Human Genetics and Biology (1525); approved statistics course; supervised semester-long internship (genetics, osteology/odontology with AMNH/NYU Dentistry/ME office)",
        "career": "Forensic anthropology, medical examiner offices, coroner, law enforcement, mass disaster teams, museum curation, PhD preparation",
        "requirements": "BA/BS preferably in anthropology, biology, or natural sciences; transcripts; Statement of Academic Purpose; CV; letters of recommendation; non-refundable application fee",
        "website": "https://gsas.nyu.edu/admissions/arc/programs/anthropology.html",
    },
    {
        "id": "ubc-mj",
        "s": "ubc",
        "n": "新闻学硕士",
        "en": "Master of Journalism (MJ)",
        "deg": "MJ",
        "lvl": "m",
        "stem": 0,
        "dur": "1-2 years full-time (Vancouver on-campus)",
        "ddl": "Check program site; typical Fall intake early (待补 exact ddl)",
        "lang": "TOEFL iBT 104 (R22/W21/S21/L22) OR IELTS Academic 7.5 (min 6.5 each) OR Duolingo 140",
        "test": '{"cls":"No GRE required for UBC MJ"}',
        "tui": "Refer to UBC Faculty of Graduate and Postdoctoral Studies international tuition schedule (待补 exact figure)",
        "url": "details/ubc-mj.html",
        "school": "University of British Columbia",
        "school_en": "University of British Columbia",
        "school_short": "UBC",
        "college": "School of Journalism, Writing, and Media (JWAM), UBC Vancouver",
        "intro": "Professional journalism master's combining practice and theory with graduate-level academic study. Designed both for working journalists and for graduates without professional experience who demonstrate superior writing and research ability.",
        "curriculum": "42 credits total: 21 required journalism practice credits + 12 journalism electives + 9 academic credits outside journalism (max 3 at 300-400 undergrad level); Journalism Practice, Media Studies, Directed Studies, Research and Writing",
        "career": "Print/broadcast/digital journalism, investigative reporting, media production, communications",
        "requirements": "4-year bachelor's degree any discipline; B+ average in upper-level (300/400) courses; 1-2 page letter of intent/cover letter; CV; portfolio of work (journalism samples OR original manuscript for non-journalists); official transcripts; 3 references (preferably all academic, minimum 2 academic)",
        "website": "https://jwam.ubc.ca/graduate/admissions/",
    },
]

# Build detail HTML pages (English content, safe template)
DETAIL_TMPL = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{school} {en} | Project Library</title>
<style>
body{{font-family:-apple-system,Segoe UI,Helvetica,Arial,sans-serif;max-width:980px;margin:24px auto;padding:0 20px;color:#222;line-height:1.6}}
h1{{font-size:22px;border-bottom:2px solid #3366cc;padding-bottom:8px}}
h2{{font-size:16px;color:#3366cc;margin-top:24px}}
.card{{background:#f7f9fc;border:1px solid #dce4f1;border-radius:8px;padding:14px 18px;margin:10px 0}}
.meta b{{display:inline-block;min-width:130px;color:#555}}
.tag{{display:inline-block;background:#e8f0fe;color:#1a56c4;padding:2px 8px;border-radius:10px;font-size:12px;margin-right:6px}}
a{{color:#3366cc}}
</style>
</head>
<body>
<h1>{school} — {en}</h1>
<div class="card meta">
<div><b>School:</b> {school}</div>
<div><b>College:</b> {college}</div>
<div><b>Degree:</b> {deg} <span class="tag">MA</span><span class="tag">lvl={lvl}</span>{stem_tag}</div>
<div><b>Duration:</b> {dur}</div>
<div><b>Deadline:</b> {ddl}</div>
<div><b>English:</b> {lang}</div>
<div><b>Standardized Test:</b> {test_cls}</div>
<div><b>Tuition:</b> {tui}</div>
</div>

<h2>Program Overview</h2>
<div class="card">{intro}</div>

<h2>Curriculum</h2>
<div class="card">{curriculum}</div>

<h2>Career Outcomes</h2>
<div class="card">{career}</div>

<h2>Admission Requirements</h2>
<div class="card">{requirements}</div>

<h2>Official Website</h2>
<div class="card"><a href="{website}" target="_blank" rel="noopener">{website}</a></div>

<p style="color:#888;font-size:12px;margin-top:24px">Note: Fields marked "待补" are not published on the official source retrieved and will be updated on a later verification pass. Test scores described are admission distribution, not minimum thresholds.</p>
</body>
</html>
"""

for p in PROGRAMS:
    stem_tag = '<span class="tag">STEM</span>' if p["stem"] == 1 else ""
    html = DETAIL_TMPL.format(
        school=p["school"], en=p["en"], deg=p["deg"], lvl=p["lvl"], stem_tag=stem_tag,
        college=p["college"], dur=p["dur"], ddl=p["ddl"], lang=p["lang"],
        test_cls=p["test"].replace('{"cls":"','').replace('"}',''),
        tui=p["tui"], intro=p["intro"], curriculum=p["curriculum"],
        career=p["career"], requirements=p["requirements"], website=p["website"],
    )
    path = os.path.join(ROOT, p["url"])
    with open(path, "w", encoding="utf-8") as f:
        f.write(html)
    print("Wrote:", p["url"])

# Append to PROGRAMS array in index_main.html
with open(IDX, "r", encoding="utf-8") as f:
    html = f.read()

def make_prog(p):
    # key names without quotes, matching existing format
    return ('{id:"%s",s:"%s",n:"%s",en:"%s",deg:"%s",lvl:"%s",stem:%d,dur:"%s",ddl:"%s",lang:"%s",test:%s,tui:"%s",url:"%s"}'
            % (p["id"], p["s"], p["n"], p["en"], p["deg"], p["lvl"], p["stem"],
               p["dur"].replace('"', "'"), p["ddl"].replace('"', "'"),
               p["lang"].replace('"', "'"), p["test"],
               p["tui"].replace('"', "'"), p["url"]))

# Locate PROGRAMS array end by bracket depth
def find_array_end(text, start_marker):
    idx = text.find(start_marker)
    if idx < 0:
        raise RuntimeError("marker not found: " + start_marker)
    # find the opening '['
    i = text.find("[", idx)
    depth = 1
    j = i + 1
    while j < len(text) and depth > 0:
        c = text[j]
        if c == '[':
            depth += 1
        elif c == ']':
            depth -= 1
        j += 1
    return i, j  # j is position after closing ']'

# Find PROGRAMS = [ ... ];
start_marker = "const PROGRAMS=["
i, j = find_array_end(html, start_marker)
# j is just after the closing ']'
# We want to insert before ']'
insert_pos = j - 1
# Check the char immediately before ']' to decide comma
prefix = html[:insert_pos].rstrip()
suffix = html[insert_pos:]  # starts with '\n];' or '];'
new_entries = ",\n" + ",\n".join(make_prog(p) for p in PROGRAMS)
# If prefix ends with '}' or ']' (last entry), add comma; if empty array, no leading comma
if prefix.rstrip().endswith("}") or prefix.rstrip().endswith("]"):
    insertion = new_entries
else:
    insertion = new_entries.lstrip(",\n")
new_html = html[:insert_pos] + insertion + "\n" + html[insert_pos:]

# Now append VD entries to VERIFIED_DETAILS Set
vd_marker = "const VERIFIED_DETAILS=new Set(["
vi, vj = find_array_end(new_html, vd_marker)
# vj is after ']'
vd_insert_pos = vj - 1
# collect urls
vd_urls = [p["url"] for p in PROGRAMS]
# Check which are already in set to avoid dup
existing = new_html[vi:vj]
to_add = [u for u in vd_urls if ('"%s"' % u) not in existing]
if to_add:
    vd_new = ",\n" + ",\n".join('"%s"' % u for u in to_add)
    vd_prefix = new_html[:vd_insert_pos].rstrip()
    if vd_prefix.endswith('"') or vd_prefix.endswith("]"):
        vd_insertion = vd_new
    else:
        vd_insertion = vd_new.lstrip(",\n")
    new_html = new_html[:vd_insert_pos] + vd_insertion + "\n" + new_html[vd_insert_pos:]

with open(IDX, "w", encoding="utf-8") as f:
    f.write(new_html)
print("Appended %d PROGRAMS entries and %d VD entries" % (len(PROGRAMS), len(to_add)))
print("Done. File size:", len(new_html))
