import re, os, json

# ============================================================
# Round 288: Add 5 programs
# 1. USC Biostatistics PhD (Keck)
# 2. USC ECE MS (Viterbi)
# 3. USC Spatial Data Science MS (Viterbi + Dornsife)
# 4. USC Physical Biology PhD (Dornsife Physics)
# 5. USC Molecular Microbiology and Immunology MS (Keck)
# ============================================================

HTML_PATH = 'index_main.html'
DETAILS_DIR = 'details'

PAGES = {
    'usc-biostat-phd': {
        'school': 'University of Southern California',
        'dept': 'Keck School of Medicine, Department of Population and Public Health Sciences',
        'website': 'https://keck.usc.edu/biostatistics-phd-program/admission-requirements/',
        'n': '生物统计学博士',
        'en': 'PhD in Biostatistics',
        'deg': 'PhD',
        'lvl': 'd',
        'stem': 1,
        'dur': '5 years',
        'ddl': 'December 1 (Fall entry)',
        'lang': 'TOEFL / IELTS (USC Graduate minimum)',
        'test': 'GRE Required (official scores required; ETS school code 4852; no department code)',
        'tui': 'Full funding package available for PhD students (tuition + stipend + health benefits)',
        'overview': 'The PhD in Biostatistics at the USC Keck School of Medicine trains researchers in statistical methodology for biomedical research. The program prepares students for academic careers and leadership roles in public health, pharmaceutical, and biotech industries. Students develop expertise in study design, data analysis, and statistical methodology development.',
        'requirements': 'Bachelor\'s degree; minimum cumulative GPA 3.0; official transcripts from each accredited institution; minimum 3 letters of recommendation (at least one academic; all letters less than one year old on department letterhead); supplemental questions; CV/resume; GRE scores (official, ETS code 4852); English proficiency for international applicants.',
        'research': 'Curriculum covers statistical theory, biostatistical methods, longitudinal data analysis, survival analysis, Bayesian methods, and statistical computing. Students collaborate with research teams in the Keck School of Medicine and USC Healthcare on real-world biomedical studies.'
    },
    'usc-ece-ms': {
        'school': 'University of Southern California',
        'dept': 'Viterbi School of Engineering, Ming Hsieh Department of Electrical and Computer Engineering',
        'website': 'https://viterbigradadmission.usc.edu/programs/masters/msprograms/electrical-computer-engineering/ms-electrical-and-computer-engineering/',
        'n': '电子与计算机工程硕士',
        'en': 'MS in Electrical and Computer Engineering',
        'deg': 'MS',
        'lvl': 'm',
        'stem': 1,
        'dur': '1.5-2 years (30-33 units)',
        'ddl': 'Fall: Dec 15 (scholarship) / Jan 15 (final); Spring: Oct 15',
        'lang': 'TOEFL / IELTS (USC Viterbi minimum)',
        'test': 'GRE Not Required for 2027 applications',
        'tui': 'Tuition per unit approximately $2,300 (2026-27); 30-33 units total',
        'overview': 'The MS in Electrical and Computer Engineering at USC Viterbi offers broad training across electrical engineering and computer engineering. Students can choose from concentrations including computer architecture, analog/mixed-signal/RF circuits, electric power, and more. The program prepares graduates for industry careers in semiconductor, telecommunications, and technology sectors, or for further PhD study.',
        'requirements': 'Bachelor\'s degree in engineering or closely related field (electronics, computer science, math, physics); transcripts; resume/CV; personal statement; letter of recommendation (optional); strong proficiency in linear circuits, linear systems, and mathematics.',
        'research': 'Concentrations: Computer Architecture, Analog/Mixed-Signal/RF Integrated Circuits, Electric Power, and general ECE. Research areas include VLSI, signal processing, communications, photonics, and control systems. Thesis option available.'
    },
    'usc-spds-ms': {
        'school': 'University of Southern California',
        'dept': 'Viterbi School of Engineering × Dornsife College, Spatial Sciences Institute',
        'website': 'https://datascience.usc.edu/academics/master-of-science-in-spatial-data-science/',
        'n': '空间数据科学硕士',
        'en': 'MS in Spatial Data Science (SPDS)',
        'deg': 'MS',
        'lvl': 'm',
        'stem': 1,
        'dur': '2 years (32 units)',
        'ddl': 'Fall: Dec 15 (merit scholarship) / Jan 15 (final); Spring: Aug 31 (merit) / Sep 15 (final)',
        'lang': 'TOEFL / IELTS (USC Graduate minimum)',
        'test': 'GRE Not Required (since September 2021)',
        'tui': 'Tuition per unit approximately $2,300 (2026-27); 32 units total',
        'overview': 'The MS in Spatial Data Science is a cross-disciplinary joint degree offered by the Viterbi School of Engineering and the Dornsife College of Letters, Arts and Sciences. Students must be admitted by both schools. The program combines data science with spatial analysis, preparing graduates for careers in geospatial analytics, urban planning, environmental monitoring, and location-based technology.',
        'requirements': 'Bachelor\'s degree in STEM (science, technology, engineering, math) or related social science; minimum cumulative GPA 3.0; programming experience or at least one year of calculus; transcripts; resume/CV; personal statement; 2 letters of recommendation (highly recommended); English proficiency for international students.',
        'research': 'Core curriculum covers information engineering, spatial analysis, geospatial data management, and machine learning for spatial data. Electives include remote sensing, GIS, urban informatics, and spatial statistics. Practicum/capstone project with industry or government partners.'
    },
    'usc-physical-bio-phd': {
        'school': 'University of Southern California',
        'dept': 'Dornsife College, Department of Physics and Astronomy',
        'website': 'https://dornsife.usc.edu/physics/graduate-admissions/',
        'n': '物理生物学博士',
        'en': 'PhD in Physical Biology (PBIO)',
        'deg': 'PhD',
        'lvl': 'd',
        'stem': 1,
        'dur': '5-6 years (60 units minimum)',
        'ddl': 'December 15 (materials); December 22 (recommendation letters)',
        'lang': 'TOEFL required for international students applying for TAship',
        'test': 'General GRE Not Required; Physics Subject GRE Not Required (for PBIO program)',
        'tui': 'Full funding package (tuition waiver + stipend + health benefits); no application fee',
        'overview': 'The PhD in Physical Biology at USC Dornsife is an interdisciplinary program bridging physics, chemistry, biology, and engineering. Students develop expertise in core biophysics through flexible, multidisciplinary coursework and accelerated transition into research. The program welcomes applicants from physics, chemistry, biology, biochemistry, mathematics, and engineering backgrounds.',
        'requirements': 'Bachelor\'s or master\'s degree in physical biology-related field (molecular biology, biochemistry, bioengineering, physics, biophysics, chemistry, etc.); transcripts; personal statement explaining research interests; 3 letters of recommendation; TOEFL for international TA applicants; no application fee.',
        'research': 'Research areas include single-molecule biophysics, membrane biophysics, computational biophysics, systems biology, and biophysics of disease. Students work with faculty across Physics, Biology, Chemistry, and Biomedical Engineering departments. Flexible curriculum allows rapid transition to research.'
    },
    'usc-mmi-ms': {
        'school': 'University of Southern California',
        'dept': 'Keck School of Medicine, Department of Molecular Microbiology and Immunology',
        'website': 'https://keck.usc.edu/molecular-microbiology-and-immunology-program/admissions-requirements/',
        'n': '分子微生物学与免疫学硕士',
        'en': 'MS in Molecular Microbiology and Immunology',
        'deg': 'MS',
        'lvl': 'm',
        'stem': 1,
        'dur': '2 years',
        'ddl': 'May 1 (Fall entry)',
        'lang': 'TOEFL / IELTS (USC Graduate minimum)',
        'test': 'GRE Not Required; MCAT optional (may be submitted)',
        'tui': 'Tuition per unit approximately $2,300 (2026-27)',
        'overview': 'The MS in Molecular Microbiology and Immunology at the USC Keck School of Medicine prepares students for careers in biomedical research, with focus on microbiology, virology, immunology, and cancer research. The program combines theoretical coursework with hands-on laboratory research at the Health Sciences Campus (Keck Medical School, School of Pharmacy, Norris Comprehensive Cancer Center, and Children\'s Hospital Los Angeles).',
        'requirements': 'Bachelor\'s degree in science (biology, chemistry, or physics); minimum undergraduate GPA 3.0; required prerequisites: one year biology, chemistry through organic chemistry, mathematics through calculus, one year physics; statement of purpose (1-2 pages); resume/CV; 3 letters of recommendation (at least 2 academic); GRE not required.',
        'research': 'Research areas include microbial pathogenesis, viral immunology, cancer immunology, vaccine development, and host-pathogen interactions. Students complete a research thesis project in a faculty laboratory on the Health Sciences Campus or at Children\'s Hospital Los Angeles.'
    }
}

def build_page_html(key, info):
    stem_label = 'STEM' if info['stem'] == 1 else 'Non-STEM'
    lvl_label = 'PhD' if info['lvl'] == 'd' else 'Master'
    duration = info['dur']
    test_cls = info['test']
    
    html = f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{info['en']} | {info['school']}</title>
<style>
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 900px; margin: 0 auto; padding: 20px; line-height: 1.6; color: #333; }}
h1 {{ color: #1a365d; border-bottom: 3px solid #3182ce; padding-bottom: 10px; }}
h2 {{ color: #2c5282; margin-top: 30px; }}
.meta {{ display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin: 20px 0; }}
.card {{ background: #f7fafc; border-left: 4px solid #3182ce; padding: 15px; border-radius: 4px; }}
.card h3 {{ margin-top: 0; color: #2c5282; font-size: 14px; text-transform: uppercase; }}
.badge {{ display: inline-block; background: #e6fffa; color: #234e52; padding: 2px 10px; border-radius: 12px; font-size: 12px; margin-right: 5px; }}
a {{ color: #3182ce; }}
</style>
</head>
<body>
<h1>{info['en']}</h1>
<p><strong>{info['school']}</strong> | {info['dept']}</p>
<p><span class="badge">{lvl_label}</span><span class="badge">{stem_label}</span><span class="badge">{info['deg']}</span></p>

<div class="meta">
  <div class="card"><h3>Duration</h3><p>{duration}</p></div>
  <div class="card"><h3>Deadline</h3><p>{info['ddl']}</p></div>
  <div class="card"><h3>English Requirement</h3><p>{info['lang']}</p></div>
  <div class="card"><h3>Standardized Test</h3><p>{test_cls}</p></div>
</div>

<div class="card"><h3>Funding / Tuition</h3><p>{info['tui']}</p></div>

<h2>Program Overview</h2>
<p>{info['overview']}</p>

<h2>Admission Requirements</h2>
<p>{info['requirements']}</p>

<h2>Research / Curriculum</h2>
<p>{info['research']}</p>

<h2>Official Website</h2>
<p><a href="{info['website']}" target="_blank">{info['website']}</a></p>
</body>
</html>'''
    return html


def append_to_programs(html_text, new_entries):
    m = re.search(r'const PROGRAMS\s*=\s*\[', html_text)
    if not m:
        raise ValueError("PROGRAMS array not found")
    start = m.end() - 1
    depth = 1
    i = start + 1
    while i < len(html_text) and depth > 0:
        if html_text[i] == '[':
            depth += 1
        elif html_text[i] == ']':
            depth -= 1
        i += 1
    end_pos = i - 1
    block = ''
    for entry in new_entries:
        block += ',' + '\n{' + entry + '}'
    new_html = html_text[:end_pos] + block + html_text[end_pos:]
    return new_html


def append_to_vd(html_text, new_urls):
    m = re.search(r'const VERIFIED_DETAILS\s*=\s*new\s+Set\s*\(\s*\[', html_text)
    if not m:
        raise ValueError("VERIFIED_DETAILS Set not found")
    start = m.end() - 1
    depth = 1
    i = start + 1
    while i < len(html_text) and depth > 0:
        if html_text[i] == '[':
            depth += 1
        elif html_text[i] == ']':
            depth -= 1
        i += 1
    end_pos = i - 1
    block = ''
    for url in new_urls:
        block += f',"{url}"'
    new_html = html_text[:end_pos] + block + html_text[end_pos:]
    return new_html


def main():
    # Step 1: Write detail pages
    for key, info in PAGES.items():
        html = build_page_html(key, info)
        path = os.path.join(DETAILS_DIR, f'{key}.html')
        with open(path, 'w', encoding='utf-8') as f:
            f.write(html)
        print(f"Written: {path}")
    
    # Step 2: Read index_main.html
    with open(HTML_PATH, 'r', encoding='utf-8') as f:
        html = f.read()
    
    before_size = len(html.encode('utf-8'))
    print(f"Before size: {before_size} bytes")
    
    # Step 3: Build PROGRAMS entries
    new_entries = []
    vd_urls = []
    for key, info in PAGES.items():
        url = f'details/{key}.html'
        vd_urls.append(url)
        
        entry = (
            f'id:"{key}",'
            f's:"usc",'
            f'n:"{info["n"]}",'
            f'en:"{info["en"]}",'
            f'deg:"{info["deg"]}",'
            f'lvl:"{info["lvl"]}",'
            f'stem:{info["stem"]},'
            f'dur:"{info["dur"]}",'
            f'ddl:"{info["ddl"]}",'
            f'lang:"{info["lang"]}",'
            f'test:{{cls:"{info["test"]}"}},'
            f'tui:"{info["tui"]}",'
            f'url:"{url}"'
        )
        new_entries.append(entry)
    
    # Step 4: Append to PROGRAMS
    html = append_to_programs(html, new_entries)
    print(f"PROGRAMS appended: {len(new_entries)} entries")
    
    # Step 5: Append to VD (re-scan after PROGRAMS insertion)
    html = append_to_vd(html, vd_urls)
    print(f"VD appended: {len(vd_urls)} urls")
    
    # Step 6: Write back
    with open(HTML_PATH, 'w', encoding='utf-8') as f:
        f.write(html)
    
    after_size = len(html.encode('utf-8'))
    print(f"After size: {after_size} bytes")
    print(f"Delta: +{after_size - before_size} bytes")
    print("Done!")


if __name__ == '__main__':
    main()
