import re, os, json

# ============================================================
# Round 287: Add 5 programs
# 1. UofT Rotman PhD in Management
# 2. Waterloo PhD in Accounting
# 3. NYU MS Applied Statistics for Social Science Research (A3SR)
# 4. CMU MS in Product Management (Tepper)
# 5. USC PIBBS PhD (Programs in Biomedical and Biological Sciences)
# ============================================================

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

PAGES = {
    'ut-management-phd': {
        'school': 'University of Toronto',
        'dept': 'Rotman School of Management',
        'website': 'https://www.sgs.utoronto.ca/programs/management-phd/',
        'n': '管理学博士',
        'en': 'PhD in Management',
        'deg': 'PhD',
        'lvl': 'd',
        'stem': 0,
        'dur': '4-5 years',
        'ddl': 'January 15 (Fall entry)',
        'lang': 'TOEFL 93 (W/S 22) / IELTS 7.0 (6.5 each) / DET 120',
        'test': 'GMAT or GRE Optional (SGS: No standardized tests required; Rotman: GMAT/GRE optional)',
        'tui': 'Full funding package available (scholarship + assistantship); domestic and international students eligible',
        'overview': 'The PhD in Management at the Rotman School of Management, University of Toronto is a research-intensive doctoral program preparing students for academic careers at leading research universities. The program offers major fields including Accounting, Finance, Marketing, Operations Management & Statistics, Organizational Behavior & Human Resource Management, and Strategic Management. Students complete coursework, a research project, comprehensive exams, and a dissertation over 4-5 years. Direct entry from bachelor\'s degree is possible with a minimum A- GPA.',
        'requirements': 'Minimum B+ average; direct entry from bachelor\'s requires A- average; transcripts; letter of intent; CV; two reference letters; GMAT/GRE optional; English proficiency proof. No supervisor required before admission (assigned by graduate unit after admission).',
        'research': 'Major fields: Accounting, Finance, Marketing, Operations Management & Statistics, Organizational Behavior & HRM, Strategic Management. First two years: coursework and research project; summer of year 2: comprehensive exam; years 3-5: dissertation research.'
    },
    'uw-accounting-phd': {
        'school': 'University of Waterloo',
        'dept': 'School of Accounting and Finance',
        'website': 'https://uwaterloo.ca/future-graduate-students/programs/by-faculty/arts/accounting-doctor-philosophy-phd',
        'n': '会计学博士',
        'en': 'PhD in Accounting',
        'deg': 'PhD',
        'lvl': 'd',
        'stem': 0,
        'dur': '4 years (48 months)',
        'ddl': 'December 1 (international) / January 15 (domestic) for Fall entry',
        'lang': 'TOEFL 100 (W/S 26) / IELTS 7.5 (W/S 7.0)',
        'test': 'GMAT or GRE Required (submission of score report mandatory)',
        'tui': 'Full-time research program; funding available through teaching and research assistantships',
        'overview': 'The PhD in Accounting at the University of Waterloo School of Accounting and Finance is the largest accounting PhD program in Canada. Founded in 1988, it trains researchers for academic careers. The program admits approximately 3-4 students per year. Students from diverse backgrounds including economics, mathematics, statistics, and behavioral science are encouraged to apply. The program emphasizes social science methodology with strong quantitative training.',
        'requirements': 'Master\'s degree or Honours Bachelor\'s degree with at least 80% average; three letters of reference; GMAT or GRE score; résumé; supplementary information form; English proficiency. Preferred math background: at least one university-level calculus course and one linear algebra course (for science/math students, not business students).',
        'research': 'Research areas include empirical/archival research, accounting judgment and decision-making, financial accounting, managerial accounting, taxation, and audit. Coursework in first two terms (up to four terms including prerequisites); dissertation research in subsequent years.'
    },
    'nyu-a3sr-ms': {
        'school': 'New York University',
        'dept': 'Steinhardt School of Culture, Education, and Human Development',
        'website': 'https://steinhardt.nyu.edu/degree/ms-applied-statistics-social-science-research',
        'n': '社会科学研究应用统计硕士',
        'en': 'MS in Applied Statistics for Social Science Research (A3SR)',
        'deg': 'MS',
        'lvl': 'm',
        'stem': 1,
        'dur': '2 years (34-44 credits, variable)',
        'ddl': 'February 1 (Fall entry)',
        'lang': 'TOEFL 105 / IELTS 7.5 / DET 125 (successful candidates typically score at or above)',
        'test': 'GRE Optional (holistic review; applications without GRE not disadvantaged)',
        'tui': 'Tuition per credit approximately $1,726 (2025-26 academic year); 34-44 credits total',
        'overview': 'The MS in Applied Statistics for Social Science Research (A3SR) at NYU Steinhardt provides rigorous training in applied statistics and quantitative research techniques for social, behavioral, and health sciences. The program offers flexible credit structure (34-44 credits) with three concentration options: Computational Methods, Data Science for Social Impact, and General Applied Statistics. Graduates pursue careers as applied statisticians, data scientists, or continue to doctoral study.',
        'requirements': 'Bachelor\'s degree; strong quantitative background; résumé/CV; statement of purpose; letters of recommendation; transcripts; English proficiency. Online competency exam in mathematics and statistics required after acceptance for course placement.',
        'research': 'Curriculum includes statistical modeling, R programming, generalized linear models, large databases, and practicum courses in social science research methodology. Hands-on projects with real-world social science data; prepares students for both industry careers and PhD study.'
    },
    'cmu-mspm-ms': {
        'school': 'Carnegie Mellon University',
        'dept': 'Tepper School of Business',
        'website': 'https://www.cmu.edu/tepper/programs/master-product-management/',
        'n': '产品管理硕士',
        'en': 'MS in Product Management',
        'deg': 'MS',
        'lvl': 'm',
        'stem': 1,
        'dur': '12 months',
        'ddl': 'Round-based (early rounds Aug 1 / Sep 1; final round spring)',
        'lang': 'TOEFL iBT 84 / IELTS Academic 7.0',
        'test': 'GMAT or GRE Required (waiver available upon request with letter to admissions committee)',
        'tui': 'GMAT program code 69H-XH-84; GRE institution code 4883; application fee $125',
        'overview': 'The MS in Product Management at Carnegie Mellon Tepper School of Business combines rigorous product strategy training with CMU\'s signature strength in computing and engineering. The program prepares graduates for technical product leadership roles. It is a STEM-designated program integrating business, technology, and design thinking. The curriculum covers product strategy, user research, data analytics, and go-to-market execution.',
        'requirements': 'Online application; current resume; required essays; two professional recommendations; unofficial transcripts; GMAT/GRE score (or approved waiver); TOEFL/IELTS/Duolingo score. Minimum GPA 3.0. Undergraduate degree in any field; technical background recommended but not required.',
        'research': 'Curriculum includes product strategy, user-centered design, product analytics, pricing and monetization, technology strategy, and leadership. Students work on real-world product projects with industry partners; capstone project integrates all learning.'
    },
    'usc-pibbs-phd': {
        'school': 'University of Southern California',
        'dept': 'Keck School of Medicine',
        'website': 'https://keck.usc.edu/pibbs/',
        'n': '生物医学与生物科学博士项目（PIBBS）',
        'en': 'PhD Programs in Biomedical and Biological Sciences (PIBBS)',
        'deg': 'PhD',
        'lvl': 'd',
        'stem': 1,
        'dur': '5-6 years',
        'ddl': 'November 15 (for full consideration, Fall entry)',
        'lang': 'TOEFL / IELTS / DET (USC graduate minimum)',
        'test': 'GRE Not Required (per Keck School of Medicine policy)',
        'tui': 'Full funding: tuition waiver + annual stipend + health/dental/vision coverage for all years in good academic standing',
        'overview': 'PIBBS (Programs in Biomedical and Biological Sciences) is the single interdisciplinary gateway for five PhD tracks at the USC Keck School of Medicine. Students enter a shared first year of laboratory rotations and core coursework, then match to a thesis mentor in one of five PhD tracks. Faculty hold appointments across Keck School of Medicine, USC School of Pharmacy, and Children\'s Hospital Los Angeles.',
        'requirements': 'Bachelor\'s degree in natural sciences (biology, physiology, engineering, chemistry, or computer science); minimum 3.0 GPA; three letters of recommendation (one from a wet-lab or computational research mentor); personal statement; research statement; demonstrated research experience; application fee $120.',
        'research': 'Five PhD tracks: CBG (Cell and Molecular Biology), DSR (Development, Stem Cell, and Regenerative Medicine), IDIP (Immunology, Disease, and Intervention), MBPH (Molecular Biology and Quantitative Biology), MMED (Molecular Medicine and Drug Discovery). First year: 29 units of core classes + lab rotations; subsequent years: thesis research.'
    }
}

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):
    """Append new PROGRAMS entries to the PROGRAMS array using bracket-depth matching."""
    # Find PROGRAMS array start
    m = re.search(r'const PROGRAMS\s*=\s*\[', html_text)
    if not m:
        raise ValueError("PROGRAMS array not found")
    
    start = m.end() - 1  # position of '['
    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  # position of closing ']'
    
    # Build new block
    block = ''
    for entry in new_entries:
        block += ',' + '\n{' + entry + '}'
    
    # Insert before closing ]
    new_html = html_text[:end_pos] + block + html_text[end_pos:]
    return new_html


def append_to_vd(html_text, new_urls):
    """Append new VERIFIED_DETAILS URLs to the Set using bracket-depth matching."""
    # Find VERIFIED_DETAILS Set start
    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  # position of '['
    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  # position of closing ']'
    
    # Build new block
    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:"{info["school"].split()[0].lower() if info["school"].startswith("University of") else info["school"].split()[0].lower()}",'
            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 (must re-scan after PROGRAMS insertion shifts positions)
    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()
