"""r285: add 5 independent PhD — MIT PoliSci / MIT Linguistics / MIT Philosophy / McGill Math / UofT MIE."""
import re
from pathlib import Path

ROOT = Path(r"D:\work buddy\2026-11-05-14-15-52")
IDX = ROOT / "index_main.html"
DETAILS = ROOT / "details"

PAGES = {
    "mit-polisci-phd": {
        "id": "mit-polisci-phd",
        "s": "mit",
        "n": "MIT政治科学博士",
        "en": "PhD in Political Science",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5 years (typical)",
        "ddl": "Dec 15, 2026 at 11:59pm ET (Fall 2027 entry; application opens Oct 1)",
        "lang": "TOEFL iBT 100 / IELTS Academic 7.0 / DET 135 (MIT OGS recommended minimum)",
        "test": "GRE General: REQUIRED (no minimum score but competitive review); ETS code 3514",
        "tui": "Fully funded (tuition + stipend) for 5 years; no separate master's required for PhD applicants",
        "url": "details/mit-polisci-phd.html",
        "school": "Massachusetts Institute of Technology",
        "dept": "Department of Political Science (School of Humanities, Arts, and Social Sciences)",
        "website": "https://polisci.mit.edu/graduate/admissions",
        "overview": "The PhD in Political Science at MIT is a research-intensive doctoral program offered by the Department of Political Science. The program trains students for academic careers and research leadership in policy, technology, and governance. MIT Political Science is not STEM-eligible (per OGS designation). The department also offers a terminal SM. Affiliated interdisciplinary programs include the Interdisciplinary Doctoral Program in Statistics (IDPS). No master's degree is required before applying to the PhD.",
        "requirements": "Bachelor's degree in any field (undergraduate political science not required, but significant coursework in political science, history, economics, philosophy, psychology, or sociology is encouraged); GRE General required (institution code 3514); TOEFL 100 / IELTS 7.0 / DET 135 minimum; application fee $90; two of six major fields must be elected: American politics, comparative politics, international relations, models and methods, political economy, security studies; reading proficiency in one foreign language (2 semesters intermediate or exam) OR advanced statistics (3 semesters or exam); second-year paper + workshop; doctoral thesis.",
        "research": "Research strengths include political economy, international relations, security studies, American politics, comparative politics, and formal/quantitative models and methods. The department hosts the MIT Industrial Performance Center and collaborates with the Sloan School on political economy research."
    },
    "mit-ling-phd": {
        "id": "mit-ling-phd",
        "s": "mit",
        "n": "MIT语言学博士",
        "en": "PhD in Linguistics",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5-6 years (typical)",
        "ddl": "Dec 15, 2026 at 11:59pm ET (Fall 2027 entry; application opens Sep 15)",
        "lang": "TOEFL iBT 100 / IELTS Academic 7.0 / DET 135 / Cambridge C1 190 / C2 200",
        "test": "GRE General: NOT ACCEPTED (department does not consider GRE scores during evaluation)",
        "tui": "Fully funded (tuition + stipend) for 5 years; automatic English test waiver for native speakers or undergrad degree within last 5 years from US/Canada/UK/Ireland/Australia/NZ",
        "url": "details/mit-ling-phd.html",
        "school": "Massachusetts Institute of Technology",
        "dept": "Department of Linguistics and Philosophy (School of Humanities, Arts, and Social Sciences)",
        "website": "https://linguistics.mit.edu/graduate/admissions/application/",
        "overview": "The PhD in Linguistics at MIT is a research-intensive doctoral program offered by the Department of Linguistics and Philosophy. The program is widely regarded as one of the top theoretical linguistics programs in the world, with historical strengths in generative grammar, syntax, phonology, semantics, and psycholinguistics. MIT Linguistics offers only the PhD (no terminal master's). Decisions are communicated by early March. Fall admission only.",
        "requirements": "Bachelor's degree in linguistics or related field; GRE NOT accepted (department explicitly does not review GRE scores); TOEFL 100 / IELTS 7.0 / DET 135 minimum (institution code 3514); automatic waiver for native English speakers or applicants with undergraduate degree within the last 5 years from a US/Canada/UK/Ireland/Australia/NZ institution; application fee $90; research statement and writing sample required; decisions by early March.",
        "research": "Research areas span syntactic theory, phonological theory, semantics, morphology, psycholinguistics, language acquisition, computational linguistics, and historical linguistics. The department shares faculty and graduate training with MIT Philosophy and hosts the MIT Center for Language, Speech, and Brain."
    },
    "mit-phil-phd": {
        "id": "mit-phil-phd",
        "s": "mit",
        "n": "MIT哲学博士",
        "en": "PhD in Philosophy",
        "deg": "PhD",
        "lvl": "d",
        "stem": 0,
        "dur": "5-6 years (typical)",
        "ddl": "Jan 2, 2027 (Fall 2027 entry; application opens Sep 15)",
        "lang": "TOEFL iBT 100 / IELTS Academic 7.0 / DET 135 / Cambridge C1 190 / C2 200",
        "test": "GRE General: REQUIRED for all applicants (institution 3514 / department 2804; scores must be < 5 years old by deadline)",
        "tui": "Fully funded (tuition + stipend) for 5 years; decisions communicated by early March",
        "url": "details/mit-phil-phd.html",
        "school": "Massachusetts Institute of Technology",
        "dept": "Department of Linguistics and Philosophy (School of Humanities, Arts, and Social Sciences)",
        "website": "https://philosophy.mit.edu/admissions/",
        "overview": "The PhD in Philosophy at MIT is a research-intensive doctoral program offered by the Department of Linguistics and Philosophy. The program focuses on analytic philosophy with particular strengths in philosophy of mind, language, science, logic, metaphysics, and epistemology. MIT Philosophy offers only the PhD. The deadline (Jan 2) is notably later than most MIT departments (Dec 1-15 cluster). Decisions are communicated by early March. Fall admission only.",
        "requirements": "Bachelor's degree in philosophy or related field; GRE General required for all applicants (institution code 3514, department code 2804; scores must be less than 5 years old by the application deadline); TOEFL 100 / IELTS 7.0 / DET 135 minimum; application fee $90; writing sample required; decisions by early March.",
        "research": "Research strengths include philosophy of mind, philosophy of language, philosophy of science, logic, metaphysics, epistemology, ethics, and political philosophy. The department has deep ties to MIT's AI, linguistics, and cognitive science communities."
    },
    "mcg-math-phd": {
        "id": "mcg-math-phd",
        "s": "mcg",
        "n": "麦吉尔大学数学博士",
        "en": "PhD in Mathematics and Statistics",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4-5 years (typical)",
        "ddl": "Jan 15, 2027 (Fall 2027 entry; application opens Sep 15); Winter (Jan) entry: Jul 15 international / Sep 1 domestic",
        "lang": "TOEFL iBT 100 (20 each) / IELTS Academic 6.5 (no band < 6.0); IELTS Online and One Skill Retake NOT accepted",
        "test": "GRE: not required (per McGill GPS general policy)",
        "tui": "All admitted graduate students receive funding package (stipend + scholarship + TA); minimum 3.0/4.0 GPA; ETS code 0935 (Math dept code 072, Statistics dept code 059)",
        "url": "details/mcg-math-phd.html",
        "school": "McGill University",
        "dept": "Department of Mathematics and Statistics (Faculty of Science)",
        "website": "https://www.mcgill.ca/mathstat/graduate",
        "overview": "The PhD in Mathematics and Statistics at McGill University is a research-intensive doctoral program offered by the Department of Mathematics and Statistics. The program emphasizes specialized and challenging learning opportunities in pure mathematics, applied mathematics, probability, and statistics. The department offers MSc, PhD, and accelerated MSc (McGill undergraduates only). All admitted graduate students in the department receive a funding package combining stipend, scholarships, and teaching assistantships.",
        "requirements": "Eligible bachelor's degree with minimum 3.0/4.0 GPA; English proficiency (TOEFL iBT 100 with 20 each, or IELTS Academic 6.5; institutional TOEFL not accepted; IELTS Online and One Skill Retake NOT accepted); two letters of recommendation; personal statement; optional research proposal; application deadline Jan 15 for Fall entry; ETS institution code 0935 (Math department code 072, Statistics department code 059).",
        "research": "Research areas span pure mathematics (algebra, analysis, geometry, topology, number theory), applied mathematics (scientific computing, mathematical biology, fluid dynamics), probability, and statistics (biostatistics, statistical theory, machine learning). McGill is the top research university in Canada for mathematics and statistics."
    },
    "ut-mie-phd": {
        "id": "ut-mie-phd",
        "s": "ut",
        "n": "多伦多大学机械与工业工程博士",
        "en": "PhD in Mechanical and Industrial Engineering",
        "deg": "PhD",
        "lvl": "d",
        "stem": 1,
        "dur": "4 years (master's entry) / 5 years (direct-entry from bachelor's)",
        "ddl": "Jan 1, 2027 application fee deadline (Fall 2027 entry; window Oct 1 - Jan 1); documents due Jan 15, 2027",
        "lang": "TOEFL iBT 93 (min 22 on all components); IELTS Academic 7.0 (min 6.5 each)",
        "test": "GRE: not required (per SGS Calendar)",
        "tui": "Funding: minimum CAD 25,000/year for up to 4 years (5 years direct-entry), covering tuition and incidental fees; 'Without funding, we cannot offer admission'; ETS code 0982",
        "url": "details/ut-mie-phd.html",
        "school": "University of Toronto",
        "dept": "Department of Mechanical & Industrial Engineering (Faculty of Applied Science & Engineering)",
        "website": "https://www.mie.utoronto.ca/programs/graduate/phd/",
        "overview": "The PhD in Mechanical and Industrial Engineering (MIE) at the University of Toronto is a research-intensive doctoral program. The keystone of the program is a thesis of original work supervised by a faculty member. Students typically enter with a Master's degree, but outstanding bachelor's applicants may apply for direct entry. Full-time PhD students receive funding throughout the program. The department explicitly states: 'Without funding, we cannot offer admission.' Note: Robotics admissions have been administratively suspended (per SGS calendar).",
        "requirements": "Master's degree in engineering or related field with minimum B+ average (U of T = 77-79%); direct-entry from bachelor's for outstanding applicants; English proficiency (TOEFL 93 with 22 on all components, IELTS 7.0 with 6.5 each); application window Oct 1 - Jan 1 (application fee deadline); documents due Jan 15; 2.5 full-course equivalents (FCEs) + thesis; non-credit seminar JDE1000H in first/second session; 70% seminar attendance in Years 1-2; supervisor identified at program start.",
        "research": "Research areas include robotics (currently suspended for admissions), sustainable energy, mechatronics, advanced manufacturing, biomechanics, thermofluids, controls, industrial engineering, operations research, and applied mechanics. The department hosts the University of Toronto Institute for Robotics and the Centre for Sustainable Energy."
    },
}

TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{title} — {school}</title>
<style>
body{{font-family:-apple-system,'Segoe UI',Roboto,sans-serif;max-width:960px;margin:24px auto;padding:0 20px;color:#222;line-height:1.6;}}
h1{{color:#1a3a6c;border-bottom:2px solid #1a3a6c;padding-bottom:8px;}}
h2{{color:#1a3a6c;margin-top:28px;}}
.badge{{display:inline-block;background:#1a3a6c;color:#fff;padding:2px 10px;border-radius:12px;font-size:13px;margin-right:6px;}}
.card{{background:#f7f9fc;border-left:4px solid #1a3a6c;padding:14px 18px;margin:12px 0;border-radius:4px;}}
a{{color:#1a6fc4;}}
</style>
</head>
<body>
<h1>{title}</h1>
<p><span class="badge">{deg}</span><span class="badge">{stem_label}</span><span class="badge">{lvl_label}</span></p>
<div class="card"><strong>School:</strong> {school}<br>
<strong>Department:</strong> {dept}<br>
<strong>Website:</strong> <a href="{website}" target="_blank">{website}</a></div>

<h2>Overview</h2>
<p>{overview}</p>

<h2>Degree Requirements</h2>
<div class="card">
<strong>Duration:</strong> {duration}<br>
<strong>Application Deadline:</strong> {ddl}<br>
<strong>English Language:</strong> {lang}<br>
<strong>Standardized Tests:</strong> {test_cls}<br>
<strong>Tuition &amp; Funding:</strong> {tui}
</div>
<p>{requirements}</p>

<h2>Research Areas</h2>
<p>{research}</p>

<p style="color:#888;font-size:12px;margin-top:32px;">Verified against official department / graduate school source. Not a minimum-threshold guarantee; admitted class distributions reflect competitive review.</p>
</body>
</html>
"""


def render(p):
    stem_label = "STEM" if p["stem"] == 1 else "Non-STEM"
    lvl_label = "Doctoral" if p["lvl"] == "d" else "Master"
    return TEMPLATE.format(
        title=p["n"], school=p["school"], deg=p["deg"],
        stem_label=stem_label, lvl_label=lvl_label,
        dept=p["dept"], website=p["website"], overview=p["overview"],
        duration=p["dur"], ddl=p["ddl"], lang=p["lang"],
        test_cls=p["test"], tui=p["tui"],
        requirements=p["requirements"], research=p["research"],
    )


def append_program(html, entry):
    m = re.search(r"const\s+PROGRAMS\s*=\s*\[", html)
    if not m:
        raise RuntimeError("PROGRAMS array not found")
    start = m.end()
    depth = 1
    i = start
    while i < len(html):
        c = html[i]
        if c == "{":
            depth += 1
        elif c == "}":
            depth -= 1
        elif c == "[" and depth == 1:
            depth += 1
        elif c == "]" and depth == 1:
            break
        i += 1
    else:
        raise RuntimeError("PROGRAMS end not found")
    insert_at = i
    j = insert_at - 1
    while j > start and html[j] in " \t\n\r":
        j -= 1
    prefix = html[: j + 1]
    suffix = html[insert_at:]
    if not prefix.endswith(","):
        prefix += ","
    block = ('{{id:"{id}",s:"{s}",n:"{n}",en:"{en}",deg:"{deg}",lvl:"{lvl}",stem:{stem},'
             'dur:"{dur}",ddl:"{ddl}",lang:"{lang}",test:{{cls:"{test}"}},tui:"{tui}",url:"{url}"}}').format(
        id=entry["id"], s=entry["s"], n=entry["n"], en=entry["en"], deg=entry["deg"],
        lvl=entry["lvl"], stem=entry["stem"], dur=entry["dur"], ddl=entry["ddl"],
        lang=entry["lang"], test=entry["test"], tui=entry["tui"], url=entry["url"])
    return prefix + "\n" + block + "\n" + suffix


def append_vd(html, urls):
    m = re.search(r"const\s+VERIFIED_DETAILS\s*=\s*new\s+Set\(\[", html)
    if not m:
        raise RuntimeError("VERIFIED_DETAILS not found")
    start = m.end()
    depth = 1
    i = start
    while i < len(html):
        c = html[i]
        if c == "[":
            depth += 1
        elif c == "]":
            depth -= 1
            if depth == 0:
                break
        i += 1
    else:
        raise RuntimeError("VD end not found")
    j = i - 1
    while j > start and html[j] in " \t\n\r":
        j -= 1
    prefix = html[: j + 1]
    suffix = html[i:]
    if not prefix.endswith(",") and not prefix.endswith("["):
        prefix += ","
    additions = ",".join('"{}"'.format(u) for u in urls)
    return prefix + "\n" + additions + "\n" + suffix


def main():
    html = IDX.read_text(encoding="utf-8")
    before = len(html.encode("utf-8"))
    new_urls = []
    for pid, p in PAGES.items():
        out = DETAILS / (pid + ".html")
        out.write_text(render(p), encoding="utf-8")
        print("wrote", out)
        html = append_program(html, p)
        new_urls.append(p["url"])
    html = append_vd(html, new_urls)
    after = len(html.encode("utf-8"))
    IDX.write_text(html, encoding="utf-8")
    print(f"index_main.html: {before} -> {after} bytes (delta +{after - before})")
    print("done.")


if __name__ == "__main__":
    main()
