#!/usr/bin/env python3
"""
TriCity Health Directory – static page generator.

Generates city pages, department pages, hospital pages, doctor pages,
city+department SEO pages, hospital/doctor/department index pages,
and sitemap.xml.

Run:  python3 /app/site/_generator/generate.py
"""
import os, random, json, textwrap
from pathlib import Path

random.seed(42)

ROOT = Path(__file__).resolve().parent.parent  # /app/site
SITE_URL = "https://tricityhealth.example.com"

# ---------- DATA ----------
CITIES = {
    "chandigarh": {"name": "Chandigarh",
                   "blurb": "The City Beautiful — North India's premier healthcare hub with PGIMER, government and private institutions.",
                   "sectors": ["Sector 12","Sector 16","Sector 22","Sector 26","Sector 34","Sector 35","Industrial Area","Manimajra"],
                   "lat":30.7333, "lng":76.7794},
    "mohali":     {"name": "Mohali",
                   "blurb": "SAS Nagar — home to flagship multi-speciality hospitals along the Mohali-Chandigarh corridor.",
                   "sectors": ["Phase 1","Phase 6","Phase 7","Phase 8","Sector 62","Sector 79","Industrial Area","Aerocity"],
                   "lat":30.7046, "lng":76.7179},
    "panchkula":  {"name": "Panchkula",
                   "blurb": "Haryana's tricity hub with growing multi-speciality and trauma-care infrastructure.",
                   "sectors": ["Sector 5","Sector 6","Sector 10","Sector 11","Sector 22","Sector 26","MDC","Mansa Devi"],
                   "lat":30.6942, "lng":76.8606},
}

DEPARTMENTS = {
    "orthopedics":          ("Orthopedics",          "bone",          ["Knee replacement","Hip replacement","Spine surgery","Arthroscopy","Fracture care"], ["Arthritis","Back pain","ACL injury","Osteoporosis"]),
    "cardiology":           ("Cardiology",           "heart-pulse",   ["Angioplasty","Bypass surgery","Pacemaker implant","ECG","Echocardiography"], ["Heart attack","Hypertension","Arrhythmia","Heart failure"]),
    "neurology":            ("Neurology",            "brain",         ["EEG","Stroke care","Epilepsy management","Migraine care"], ["Stroke","Epilepsy","Migraine","Parkinson's"]),
    "neurosurgery":         ("Neurosurgery",         "scan",          ["Brain tumor surgery","Spine surgery","Aneurysm clipping"], ["Brain tumor","Spinal cord injury","Aneurysm"]),
    "oncology":             ("Oncology",             "ribbon",        ["Chemotherapy","Radiation therapy","Cancer surgery","Targeted therapy"], ["Breast cancer","Lung cancer","Lymphoma","Leukemia"]),
    "urology":              ("Urology",              "droplet",       ["Kidney stone removal","Prostate surgery","Cystoscopy","TURP"], ["Kidney stones","Enlarged prostate","UTI"]),
    "nephrology":           ("Nephrology",           "filter",        ["Dialysis","Kidney biopsy","Transplant evaluation"], ["CKD","Acute kidney injury","Glomerulonephritis"]),
    "pulmonology":          ("Pulmonology",          "wind",          ["Bronchoscopy","PFT","Sleep study","Asthma management"], ["Asthma","COPD","Pneumonia","Tuberculosis"]),
    "gastroenterology":     ("Gastroenterology",     "soup",          ["Endoscopy","Colonoscopy","ERCP","Liver biopsy"], ["GERD","Ulcer","IBS","Liver cirrhosis"]),
    "general-surgery":      ("General Surgery",      "scissors",      ["Laparoscopy","Hernia repair","Appendectomy","Gallbladder removal"], ["Hernia","Appendicitis","Gallstones"]),
    "plastic-surgery":      ("Plastic Surgery",      "sparkles",      ["Rhinoplasty","Liposuction","Reconstructive surgery"], ["Burns","Cleft lip","Cosmetic concerns"]),
    "ent":                  ("ENT",                  "ear",           ["Tonsillectomy","Septoplasty","Sinus surgery","Cochlear implant"], ["Sinusitis","Hearing loss","Vertigo","Tonsillitis"]),
    "ophthalmology":        ("Ophthalmology",        "eye",           ["Cataract surgery","LASIK","Glaucoma management","Retina surgery"], ["Cataract","Glaucoma","Diabetic retinopathy"]),
    "dermatology":          ("Dermatology",          "hand",          ["Acne treatment","Laser hair removal","Skin biopsy","Botox"], ["Acne","Eczema","Psoriasis","Vitiligo"]),
    "gynecology":           ("Gynecology",           "venus",         ["PCOS management","Hysterectomy","Colposcopy","Infertility care"], ["PCOS","Endometriosis","Menstrual disorders"]),
    "obstetrics":           ("Obstetrics",           "baby",          ["Antenatal care","C-section","Normal delivery","High-risk pregnancy"], ["Pregnancy","Pre-eclampsia","Gestational diabetes"]),
    "pediatrics":           ("Pediatrics",           "baby",          ["Vaccinations","Growth monitoring","Newborn care"], ["Fever","Asthma","Allergies","Nutrition"]),
    "neonatology":          ("Neonatology",          "baby",          ["NICU care","Preterm baby management"], ["Preterm birth","Neonatal jaundice"]),
    "psychiatry":           ("Psychiatry",           "brain",         ["Depression therapy","Anxiety care","De-addiction"], ["Depression","Anxiety","Bipolar","OCD"]),
    "psychology":           ("Psychology",           "smile",         ["CBT","Family therapy","Stress counselling"], ["Stress","Burnout","Grief"]),
    "internal-medicine":    ("Internal Medicine",    "stethoscope",   ["Health check-ups","Diabetes management","Hypertension care"], ["Diabetes","Hypertension","Thyroid"]),
    "endocrinology":        ("Endocrinology",        "activity",      ["Diabetes care","Thyroid management","Hormonal therapy"], ["Diabetes","Thyroid","PCOS","Obesity"]),
    "rheumatology":         ("Rheumatology",         "hand",          ["Joint injections","Autoimmune management"], ["Rheumatoid arthritis","Lupus","Gout"]),
    "dentistry":            ("Dentistry",            "smile",         ["Implants","Root canal","Cosmetic dentistry","Braces"], ["Cavity","Gum disease","Misaligned teeth"]),
    "physiotherapy":        ("Physiotherapy",        "dumbbell",      ["Sports rehab","Post-surgery rehab","Manual therapy"], ["Sports injury","Lower back pain"]),
    "emergency-medicine":   ("Emergency Medicine",   "siren",         ["Trauma care","Acute care","Critical stabilisation"], ["Accidents","Acute illness"]),
    "critical-care":        ("Critical Care",        "monitor",       ["ICU","Ventilator care","Sepsis management"], ["Sepsis","Respiratory failure"]),
    "radiology":            ("Radiology",            "scan-line",     ["MRI","CT scan","X-ray","Ultrasound"], ["Diagnostic imaging"]),
    "pathology":            ("Pathology",            "flask-conical", ["Blood tests","Histopathology","Cytology"], ["Lab diagnostics"]),
    "anesthesiology":       ("Anesthesiology",       "syringe",       ["General anesthesia","Regional anesthesia","Pain management"], ["Surgical anesthesia"]),
    "pain-medicine":        ("Pain Medicine",        "pill",          ["Nerve blocks","Chronic pain therapy"], ["Chronic back pain","Neuropathy"]),
    "sports-medicine":      ("Sports Medicine",      "trophy",        ["Athletic injury management","Performance care"], ["Sports injuries"]),
    "vascular-surgery":     ("Vascular Surgery",     "git-branch",    ["Varicose vein surgery","Bypass surgery"], ["Varicose veins","DVT"]),
    "cardiac-surgery":      ("Cardiac Surgery",      "heart",         ["CABG","Valve replacement","Pediatric cardiac surgery"], ["Coronary artery disease","Valve disease"]),
    "pediatric-surgery":    ("Pediatric Surgery",    "baby",          ["Congenital correction","Hernia repair in children"], ["Pediatric hernia","Congenital defects"]),
    "hepatology":           ("Hepatology",           "leaf",          ["Hepatitis management","Cirrhosis care","Liver transplant evaluation"], ["Hepatitis","Cirrhosis","Fatty liver"]),
    "infectious-diseases":  ("Infectious Diseases",  "shield",        ["Antibiotic stewardship","Travel medicine"], ["TB","HIV","Dengue"]),
    "family-medicine":      ("Family Medicine",      "users",         ["Primary care","Preventive medicine"], ["General health","Chronic disease"]),
}

# popular city x department SEO pages
CITY_DEPT_SEO = [
    ("orthopedics","Orthopedic Doctor","Orthopedic Hospital"),
    ("cardiology","Cardiologist","Cardiac Hospital"),
    ("neurology","Neurologist","Neurology Hospital"),
    ("ent","ENT Specialist","ENT Hospital"),
    ("gynecology","Gynecologist","Gynecology Hospital"),
    ("pediatrics","Pediatrician","Pediatric Hospital"),
    ("dermatology","Dermatologist","Skin Clinic"),
    ("dentistry","Dentist","Dental Clinic"),
]

# Hospital name banks per city
HOSPITAL_BANKS = {
    "chandigarh": [
        ("PGIMER Chandigarh","Sector 12","Multi-speciality"),
        ("Government Multi-Specialty Hospital 16","Sector 16","Government"),
        ("Apollo Mukat Hospital","Sector 34","Multi-speciality"),
        ("Fortis Hospital Chandigarh","Sector 26","Multi-speciality"),
        ("Healing Hospital","Sector 34","Multi-speciality"),
        ("Mukat Hospital","Sector 34","Cardiac & Neuro"),
        ("Indus Super Speciality Hospital","Sector 11","Multi-speciality"),
        ("Sood Eye Hospital","Sector 35","Eye Care"),
        ("Cheema Medical Complex","Manimajra","Multi-speciality"),
        ("Aakar IVF Centre","Sector 35","Fertility"),
        ("Grewal Eye Institute","Sector 9","Eye Care"),
        ("Silver Oaks Hospital","Sector 21","Multi-speciality"),
        ("Aastha Hospital","Sector 47","Multi-speciality"),
        ("Chandigarh Orthopedic Centre","Sector 35","Orthopedics"),
        ("Aarogya Hospital","Sector 71","Multi-speciality"),
    ],
    "mohali": [
        ("Fortis Hospital Mohali","Sector 62","Multi-speciality"),
        ("Max Super Speciality Phase 6","Phase 6","Multi-speciality"),
        ("Ivy Hospital Mohali","Sector 71","Multi-speciality"),
        ("Cheema Medical Complex Mohali","Phase 4","Multi-speciality"),
        ("Amcare Hospital","Phase 7","Multi-speciality"),
        ("Sohana Hospital","Sector 80","Cardiac & Neuro"),
        ("Maxwell Hospital","Phase 6","Multi-speciality"),
        ("Mohali Cardiac Centre","Phase 5","Cardiology"),
        ("Aashlok Hospital","Sector 62","Multi-speciality"),
        ("ManglamPlus MediCity","Sector 79","Multi-speciality"),
        ("Apex Super Speciality Hospital","Sector 70","Multi-speciality"),
        ("Healing Touch Hospital","Phase 1","Multi-speciality"),
        ("Punjab Heart Institute","Sector 79","Cardiology"),
        ("Mohali Children's Hospital","Phase 7","Pediatrics"),
        ("Skin City Mohali","Phase 5","Dermatology"),
    ],
    "panchkula": [
        ("Paras Hospital Panchkula","Sector 22","Multi-speciality"),
        ("Ojas Super Speciality Hospital","Sector 26","Multi-speciality"),
        ("Alchemist Hospital","Sector 21","Multi-speciality"),
        ("Cygnus Multi-Speciality Hospital","Sector 6","Multi-speciality"),
        ("MAX Hospital Panchkula","Sector 5","Multi-speciality"),
        ("Park Hospital","Sector 10","Multi-speciality"),
        ("Aashlok Panchkula","Sector 11","Multi-speciality"),
        ("Tagore Hospital","Sector 19","Multi-speciality"),
        ("Panchkula Heart Centre","Sector 5","Cardiology"),
        ("Sai Care Hospital","Sector 14","Multi-speciality"),
        ("Sapphire Hospital","MDC","Multi-speciality"),
        ("Polaris Hospital","Sector 25","Multi-speciality"),
        ("Eye-Q Vision","Sector 8","Eye Care"),
        ("Sparsh Children's Hospital","Sector 12A","Pediatrics"),
        ("Skin Wellness Clinic","Sector 9","Dermatology"),
    ],
}

# Doctor name banks (first, last)
FIRST_NAMES_M = ["Rajat","Vikram","Sunil","Anil","Manish","Harpreet","Karan","Aditya","Saurabh","Ankit","Rohit","Aman","Gaurav","Tanveer","Sandeep","Vivek","Nikhil","Abhinav","Rohan","Mohan","Inder","Sahil","Rishabh","Tejas","Vinod"]
FIRST_NAMES_F = ["Sanya","Meera","Neha","Pooja","Harleen","Anjali","Priya","Komal","Ritika","Simran","Nisha","Aarti","Ekta","Diksha","Tanya","Shruti","Geet","Mahima","Suman","Kavita","Rashmi","Anya","Roshni","Ira"]
LAST_NAMES = ["Arora","Khanna","Sandhu","Bhatia","Kapoor","Sharma","Verma","Gill","Aulakh","Bedi","Sodhi","Mehra","Singh","Saini","Goyal","Mehta","Bansal","Ahuja","Sehgal","Gupta","Sethi","Chopra","Mahajan","Walia","Bajaj","Dhillon","Anand","Khurana","Tandon","Sood"]

def slugify(s):
    return s.lower().replace(" ","-").replace(".","").replace(",","").replace("'","").replace("&","and")

def render_meta(title, desc, canonical):
    return f"$page_title = {repr(title)};\n  $meta_description = {repr(desc)};\n  $canonical = '{SITE_URL}{canonical}';"

# -------- BUILD DATASETS --------
def build_hospitals():
    data = []
    for city, banks in HOSPITAL_BANKS.items():
        for (name, area, focus) in banks:
            slug = slugify(name)
            depts = random.sample(list(DEPARTMENTS.keys()), random.randint(8,16))
            data.append({
                "slug": slug, "name": name, "city": city, "area": area, "focus": focus,
                "beds": random.choice([120,180,220,260,320,400,500,600]),
                "ot": random.choice([4,6,8,10,12,16]),
                "icu": random.choice([12,18,24,30,40,60]),
                "rating": round(random.uniform(4.1, 4.9), 1),
                "reviews": random.randint(120, 2400),
                "established": random.randint(1985, 2018),
                "phone": "+91-99999-9" + str(random.randint(1000,9999)),
                "emergency": True,
                "insurance": random.sample(["Star Health","HDFC ERGO","ICICI Lombard","CGHS","ECHS","Niva Bupa","Care Health","Aditya Birla"], 5),
                "departments": depts,
            })
    return data

def build_doctors():
    data = []
    dept_keys = list(DEPARTMENTS.keys())
    popular_depts = [d[0] for d in CITY_DEPT_SEO]
    for city, banks in HOSPITAL_BANKS.items():
        # First: guarantee 3 doctors per popular department per city for SEO coverage
        forced = []
        for pd in popular_depts:
            forced += [pd]*3
        # Fill remaining slots (30 total) with random departments
        remaining = max(0, 30 - len(forced))
        forced += [random.choice(dept_keys) for _ in range(remaining)]
        random.shuffle(forced)
        # 30 doctors per city
        for i in range(30):
            is_f = random.random() < 0.45
            first = random.choice(FIRST_NAMES_F if is_f else FIRST_NAMES_M)
            last  = random.choice(LAST_NAMES)
            dept  = forced[i]
            name  = f"Dr. {first} {last}"
            slug  = slugify(name + " " + city)
            # ensure uniqueness
            base_slug = slug; n=2
            while any(d['slug']==slug for d in data):
                slug = f"{base_slug}-{n}"; n+=1
            hosp = random.choice(banks)
            qual = random.choice(["MBBS, MD","MBBS, MS","MBBS, DM","MBBS, MCh","MBBS, DNB","MBBS, MD, DNB"])
            data.append({
                "slug": slug, "name": name, "first": first, "last": last,
                "qual": qual, "dept": dept, "dept_name": DEPARTMENTS[dept][0],
                "city": city, "hospital_name": hosp[0], "hospital_area": hosp[1],
                "experience": random.randint(6, 30),
                "rating": round(random.uniform(4.2, 4.95), 1),
                "reviews": random.randint(48, 920),
                "initials": (first[0] + last[0]).upper(),
                "fee": random.choice([400, 500, 600, 800, 1000, 1200, 1500]),
                "lang": random.sample(["English","Hindi","Punjabi"], 2 + random.randint(0,1)),
                "online": random.random() < 0.55,
            })
    return data

HOSPITALS = build_hospitals()
DOCTORS   = build_doctors()

def hospitals_for_city(city):
    return [h for h in HOSPITALS if h['city']==city]
def doctors_for_city(city):
    return [d for d in DOCTORS if d['city']==city]
def doctors_for_dept(dept_slug, city=None):
    return [d for d in DOCTORS if d['dept']==dept_slug and (city is None or d['city']==city)]
def hospitals_for_dept(dept_slug, city=None):
    return [h for h in HOSPITALS if dept_slug in h['departments'] and (city is None or h['city']==city)]

# -------- HELPERS for HTML fragments --------
def doctor_card(d, base=""):
    return f"""<a class="doc-card" href="{base}doctor/{d['slug']}.php" data-testid="doctor-{d['slug']}">
  <div class="doc-card__media"><span class="doc-card__avatar">{d['initials']}</span></div>
  <div class="doc-card__body">
    <h3>{d['name']}</h3>
    <div class="doc-card__qual">{d['qual']}</div>
    <span class="doc-card__spec">{d['dept_name']}</span>
    <div class="doc-card__meta">
      <div><strong>{CITIES[d['city']]['name']}</strong><span>City</span></div>
      <div><strong>{d['experience']} yrs</strong><span>Experience</span></div>
      <div><span class="rating"><svg viewBox="0 0 24 24"><polygon points="12 2 15 9 22 9.3 17 14.1 18.5 21 12 17.5 5.5 21 7 14.1 2 9.3 9 9 12 2"/></svg> {d['rating']}</span><span>{d['reviews']} reviews</span></div>
    </div>
  </div>
</a>"""

def hospital_card(h, base=""):
    tags = "".join(f"<span>{DEPARTMENTS[t][0]}</span>" for t in h['departments'][:3])
    return f"""<a class="hosp-card" href="{base}hospital/{h['slug']}.php" data-testid="hospital-{h['slug']}">
  <div class="hosp-card__media"><span class="hosp-card__city">{CITIES[h['city']]['name']}</span><i data-lucide="building-2"></i></div>
  <div class="hosp-card__body">
    <h3>{h['name']}</h3>
    <div class="hosp-card__addr"><i data-lucide="map-pin"></i> {h['area']}, {CITIES[h['city']]['name']}</div>
    <div class="hosp-card__tags">{tags}</div>
    <div class="hosp-card__foot">
      <span class="rating"><svg viewBox="0 0 24 24"><polygon points="12 2 15 9 22 9.3 17 14.1 18.5 21 12 17.5 5.5 21 7 14.1 2 9.3 9 9 12 2"/></svg> {h['rating']} <span class="count">({h['reviews']})</span></span>
      <span>View details <i data-lucide="arrow-right" style="width:14px;height:14px;vertical-align:middle"></i></span>
    </div>
  </div>
</a>"""

def dept_card(slug, base=""):
    name, icon, *_ = DEPARTMENTS[slug]
    return f"""<a class="dept-card" href="{base}department/{slug}.php" data-testid="dept-{slug}">
  <span class="dept-card__icon"><i data-lucide="{icon}"></i></span>
  <div><h3>{name}</h3><p>{DEPARTMENTS[slug][0]} specialists across the tricity.</p></div>
  <i data-lucide="arrow-up-right" class="arr"></i>
</a>"""

def faq_block(items):
    out = '<div class="faq reveal">\n'
    for q,a in items:
        out += f"<details><summary>{q}</summary><p>{a}</p></details>\n"
    out += "</div>\n"
    # JSON-LD
    ld = {"@context":"https://schema.org","@type":"FAQPage","mainEntity":[
        {"@type":"Question","name":q,"acceptedAnswer":{"@type":"Answer","text":a}} for q,a in items
    ]}
    out += f'<script type="application/ld+json">{json.dumps(ld)}</script>\n'
    return out

def write(path, content):
    p = ROOT / path
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(content)

# -------- TEMPLATE WRAPPERS --------
def page_header(php_vars, base="", active_nav="", extra_schema=""):
    inc = f'''<?php
require_once __DIR__ . '{"/../includes/data.php" if base else "/includes/data.php"}';
{php_vars}
$base = {repr(base)};
$active_nav = {repr(active_nav)};
{("$extra_schema = " + repr(extra_schema) + ";") if extra_schema else ""}
include __DIR__ . '{("/../includes/header.php") if base else ("/includes/header.php")}';
?>'''
    return inc

def page_footer(base=""):
    return f'<?php include __DIR__ . \'{"/../includes/footer.php" if base else "/includes/footer.php"}\'; ?>'

# -------- GENERATORS --------
def gen_doctor_page(d):
    base = "../"
    awards = ["Best Young Doctor 2022","Patient Choice Award","Top Reviewed Specialist"]
    memberships = ["Indian Medical Association","Association of Physicians of India",f"{d['dept_name']} Society of India"]
    edu = [f"MBBS — {random.choice(['GMCH Chandigarh','PGIMER','AIIMS','MAMC Delhi','BFUHS Faridkot'])}",
           f"{d['qual'].split(',')[-1].strip()} — {random.choice(['PGIMER','AIIMS','CMC Vellore','KEM Mumbai'])}"]
    expertise = DEPARTMENTS[d['dept']][2]
    conditions = DEPARTMENTS[d['dept']][3]
    related_docs = [x for x in DOCTORS if x['dept']==d['dept'] and x['slug']!=d['slug']][:4]
    related_hosps = [h for h in HOSPITALS if h['city']==d['city']][:3]
    
    title = f"{d['name']} — Best {d['dept_name']} in {CITIES[d['city']]['name']} | {d['qual']}"
    desc  = f"Book appointment with {d['name']} ({d['qual']}), {d['dept_name']} in {CITIES[d['city']]['name']}. {d['experience']} years experience. Patient rating {d['rating']}/5."

    php_vars = render_meta(title, desc, f"/doctor/{d['slug']}.php") + f"\n  $breadcrumbs = [['label'=>'Home','url'=>'{SITE_URL}/'], ['label'=>'Doctors','url'=>'{SITE_URL}/doctor/index.php'], ['label'=>'{d['dept_name']}','url'=>'{SITE_URL}/department/{d['dept']}.php'], ['label'=>{repr(d['name'])}]];"

    schema = json.dumps({
        "@context":"https://schema.org","@type":"Physician","name":d['name'],
        "medicalSpecialty":d['dept_name'],"telephone":"+91-99999-99999",
        "address":{"@type":"PostalAddress","streetAddress":d['hospital_area'],"addressLocality":CITIES[d['city']]['name'],"addressCountry":"IN"},
        "aggregateRating":{"@type":"AggregateRating","ratingValue":d['rating'],"reviewCount":d['reviews']}
    })
    extra_schema = f'<script type="application/ld+json">{schema}</script>'

    body = f"""
<section class="profile-hero">
  <div class="container profile-hero__inner">
    <div class="profile-hero__avatar">{d['initials']}</div>
    <div>
      <span class="hero__badge" style="background:rgba(255,255,255,.16);color:#fff;border-color:transparent;"><span class="dot"></span> Verified profile</span>
      <h1>{d['name']}</h1>
      <div class="profile-hero__qual">{d['qual']} · {d['dept_name']}</div>
      <div class="profile-hero__meta">
        <span><i data-lucide="building-2"></i>{d['hospital_name']}</span>
        <span><i data-lucide="map-pin"></i>{d['hospital_area']}, {CITIES[d['city']]['name']}</span>
        <span><i data-lucide="clock"></i>{d['experience']} yrs experience</span>
        <span><i data-lucide="star"></i>{d['rating']} ({d['reviews']} reviews)</span>
      </div>
    </div>
    <div class="profile-hero__cta">
      <a class="btn btn--light btn--lg" href="tel:<?= preg_replace('/[^0-9+]/','',$PHONE_CALL) ?>" data-testid="doctor-book"><i data-lucide="calendar-plus"></i>Book Appointment</a>
      <a class="btn btn--ghost btn--lg" style="color:#fff;border-color:rgba(255,255,255,.4);" href="https://wa.me/<?= preg_replace('/[^0-9]/','',$PHONE_WHATSAPP) ?>" target="_blank"><i data-lucide="message-circle"></i>WhatsApp</a>
    </div>
  </div>
</section>

<div class="container">
<div class="profile-body">
  <div class="profile-body__main">
    <section>
      <h2>About {d['name']}</h2>
      <p>{d['name']} is a {d['dept_name'].lower()} specialist based in {CITIES[d['city']]['name']} with over {d['experience']} years of clinical experience at {d['hospital_name']}. Known for patient-first care, evidence-based practice and clear communication, {d['first']} is regularly consulted for both routine and complex cases across the tricity region.</p>
      <p>The practice covers diagnostic evaluation, modern treatment protocols and long-term follow-up. Patients value {d['first']}'s approachable style and willingness to explain treatment options at every step.</p>
      <div class="kv-grid">
        <div class="kv"><span>Experience</span><strong>{d['experience']} yrs</strong></div>
        <div class="kv"><span>Consultation Fee</span><strong>₹{d['fee']}</strong></div>
        <div class="kv"><span>Languages</span><strong style="font-size:1rem;">{", ".join(d['lang'])}</strong></div>
      </div>
    </section>

    <section>
      <h2>Education</h2>
      <ul class="checklist">{"".join(f"<li>{e}</li>" for e in edu)}</ul>
    </section>

    <section>
      <h2>Areas of Expertise</h2>
      <div class="pill-list">{"".join(f"<span>{e}</span>" for e in expertise)}</div>
    </section>

    <section>
      <h2>Conditions Treated</h2>
      <div class="pill-list">{"".join(f"<span>{c}</span>" for c in conditions)}</div>
    </section>

    <section>
      <h2>Awards & Memberships</h2>
      <ul class="checklist">{"".join(f"<li>{a}</li>" for a in awards)}{"".join(f"<li>{m}</li>" for m in memberships)}</ul>
    </section>

    <section>
      <h2>Videos & Gallery</h2>
      <div class="grid grid--3">
        <div class="article-card"><div class="article-card__media"><i data-lucide="play-circle"></i></div><div class="article-card__body"><h3>Doctor introduction</h3><div class="article-card__meta">Video placeholder · 1:30</div></div></div>
        <div class="article-card"><div class="article-card__media"><i data-lucide="image"></i></div><div class="article-card__body"><h3>Clinic gallery</h3><div class="article-card__meta">Photos placeholder</div></div></div>
        <div class="article-card"><div class="article-card__media"><i data-lucide="play-circle"></i></div><div class="article-card__body"><h3>Patient testimonial</h3><div class="article-card__meta">Video placeholder</div></div></div>
      </div>
    </section>

    <section>
      <h2>Patient Reviews</h2>
      <div>
        <div class="review">
          <div class="review__head"><div class="hero__avatar">NK</div><div><div class="who">Neha Kapoor</div><div class="when">2 weeks ago</div></div><div class="review__rating rating"><svg viewBox="0 0 24 24"><polygon points="12 2 15 9 22 9.3 17 14.1 18.5 21 12 17.5 5.5 21 7 14.1 2 9.3 9 9 12 2"/></svg> 5.0</div></div>
          <p>Excellent doctor. Took time to explain everything and the treatment plan was effective. Highly recommend.</p>
        </div>
        <div class="review">
          <div class="review__head"><div class="hero__avatar">RS</div><div><div class="who">Ramesh Singh</div><div class="when">1 month ago</div></div><div class="review__rating rating"><svg viewBox="0 0 24 24"><polygon points="12 2 15 9 22 9.3 17 14.1 18.5 21 12 17.5 5.5 21 7 14.1 2 9.3 9 9 12 2"/></svg> 4.7</div></div>
          <p>Very professional. The clinic staff was helpful and waiting time was minimal.</p>
        </div>
        <div class="review">
          <div class="review__head"><div class="hero__avatar">PD</div><div><div class="who">Priya Dhillon</div><div class="when">3 months ago</div></div><div class="review__rating rating"><svg viewBox="0 0 24 24"><polygon points="12 2 15 9 22 9.3 17 14.1 18.5 21 12 17.5 5.5 21 7 14.1 2 9.3 9 9 12 2"/></svg> 4.9</div></div>
          <p>One of the best specialists I have consulted. Detailed and patient. Definitely going back.</p>
        </div>
      </div>
    </section>

    <section>
      <h2>FAQs</h2>
      {faq_block([
          (f"How can I book an appointment with {d['name']}?", "You can book by calling the clinic or using the WhatsApp/booking buttons above."),
          (f"What is the consultation fee?", f"The consultation fee is approximately ₹{d['fee']}. Please verify with the clinic for any updates."),
          (f"Does {d['first']} offer online consultation?", "Yes" if d['online'] else "Currently the doctor sees patients in person at the clinic."),
          (f"Where does {d['name']} practice?", f"{d['hospital_name']}, {d['hospital_area']}, {CITIES[d['city']]['name']}."),
      ])}
    </section>
  </div>

  <aside class="profile-sidebar">
    <div class="sb-card">
      <h4>Consultation</h4>
      <div class="row"><span>Fee</span><strong>₹{d['fee']}</strong></div>
      <div class="row"><span>Mode</span><strong>{"In-clinic & Online" if d['online'] else "In-clinic"}</strong></div>
      <div class="row"><span>Languages</span><strong>{", ".join(d['lang'])}</strong></div>
      <a class="btn btn--primary btn--block mt-2" href="tel:<?= preg_replace('/[^0-9+]/','',$PHONE_CALL) ?>"><i data-lucide="phone"></i>Call clinic</a>
      <a class="btn btn--ghost btn--block mt-2" href="https://wa.me/<?= preg_replace('/[^0-9]/','',$PHONE_WHATSAPP) ?>"><i data-lucide="message-circle"></i>WhatsApp</a>
    </div>
    <div class="sb-card">
      <h4>Practices at</h4>
      <p style="margin:0;font-weight:600">{d['hospital_name']}</p>
      <p class="muted" style="margin:4px 0 12px;">{d['hospital_area']}, {CITIES[d['city']]['name']}</p>
      <div class="map-placeholder"><i data-lucide="map"></i></div>
    </div>
    <div class="sb-card">
      <h4>Quick links</h4>
      <div style="display:flex;flex-direction:column;gap:6px;">
        <a href="../department/{d['dept']}.php">All {d['dept_name']} doctors</a>
        <a href="../{d['city']}/index.php">Doctors in {CITIES[d['city']]['name']}</a>
        <a href="../hospital/index.php">All hospitals</a>
      </div>
    </div>
  </aside>
</div>

<section class="section">
  <div class="section__head"><h2>Related doctors</h2></div>
  <div class="grid grid--4">{"".join(doctor_card(rd, base) for rd in related_docs)}</div>
</section>

<section class="section">
  <div class="section__head"><h2>Related hospitals</h2></div>
  <div class="grid grid--3">{"".join(hospital_card(h, base) for h in related_hosps)}</div>
</section>
</div>
"""
    content = page_header(php_vars, base="../", active_nav="doctors", extra_schema=extra_schema) + body + page_footer(base="../")
    write(f"doctor/{d['slug']}.php", content)

def gen_hospital_page(h):
    base = "../"
    departments = h['departments']
    related_docs = [d for d in DOCTORS if d['city']==h['city']][:6]
    nearby = [hh for hh in HOSPITALS if hh['city']==h['city'] and hh['slug']!=h['slug']][:3]
    facilities = ["24×7 Emergency","Pharmacy","Diagnostic Lab","Cafeteria","Ambulance Service","Patient Lounge","Wi-Fi","Insurance Desk"]
    
    title = f"{h['name']} — Multi-Speciality Hospital in {CITIES[h['city']]['name']}"
    desc = f"{h['name']} in {h['area']}, {CITIES[h['city']]['name']}. {h['beds']} beds · {h['ot']} OTs · {h['icu']} ICU beds. {len(departments)} departments. Established {h['established']}."

    php_vars = render_meta(title, desc, f"/hospital/{h['slug']}.php") + f"\n  $breadcrumbs = [['label'=>'Home','url'=>'{SITE_URL}/'], ['label'=>'Hospitals','url'=>'{SITE_URL}/hospital/index.php'], ['label'=>{repr(h['name'])}]];"

    schema = json.dumps({
        "@context":"https://schema.org","@type":"Hospital","name":h['name'],
        "address":{"@type":"PostalAddress","streetAddress":h['area'],"addressLocality":CITIES[h['city']]['name'],"addressCountry":"IN"},
        "telephone":h['phone'],
        "aggregateRating":{"@type":"AggregateRating","ratingValue":h['rating'],"reviewCount":h['reviews']},
        "medicalSpecialty":[DEPARTMENTS[d][0] for d in departments[:6]]
    })
    extra_schema = f'<script type="application/ld+json">{schema}</script>'

    body = f"""
<section class="profile-hero">
  <div class="container profile-hero__inner">
    <div class="profile-hero__avatar" style="border-radius:24px;"><i data-lucide="building-2" style="width:60px;height:60px;color:#fff"></i></div>
    <div>
      <span class="hero__badge" style="background:rgba(255,255,255,.16);color:#fff;border-color:transparent;"><span class="dot"></span> {h['focus']}</span>
      <h1>{h['name']}</h1>
      <div class="profile-hero__qual">{h['area']}, {CITIES[h['city']]['name']} · Estd. {h['established']}</div>
      <div class="profile-hero__meta">
        <span><i data-lucide="bed-double"></i>{h['beds']} beds</span>
        <span><i data-lucide="syringe"></i>{h['ot']} OTs</span>
        <span><i data-lucide="monitor"></i>{h['icu']} ICU</span>
        <span><i data-lucide="star"></i>{h['rating']} ({h['reviews']} reviews)</span>
      </div>
    </div>
    <div class="profile-hero__cta">
      <a class="btn btn--light btn--lg" href="tel:<?= preg_replace('/[^0-9+]/','',$PHONE_CALL) ?>"><i data-lucide="phone"></i>Call hospital</a>
      <a class="btn btn--ghost btn--lg" style="color:#fff;border-color:rgba(255,255,255,.4);" href="tel:<?= preg_replace('/[^0-9+]/','',$PHONE_EMERGENCY) ?>"><i data-lucide="siren"></i>Emergency</a>
    </div>
  </div>
</section>

<div class="container">
<div class="profile-body">
  <div class="profile-body__main">
    <section>
      <h2>Overview</h2>
      <p>{h['name']} is a {h['focus'].lower()} hospital located in {h['area']}, {CITIES[h['city']]['name']}. Established in {h['established']}, the hospital offers {len(departments)} departments with {h['beds']} beds, {h['ot']} operation theatres and a {h['icu']}-bed ICU. Known for round-the-clock emergency response, diagnostics and consistent patient outcomes.</p>
      <div class="kv-grid">
        <div class="kv"><span>Total beds</span><strong>{h['beds']}</strong></div>
        <div class="kv"><span>Operation Theatres</span><strong>{h['ot']}</strong></div>
        <div class="kv"><span>ICU beds</span><strong>{h['icu']}</strong></div>
      </div>
    </section>

    <section>
      <h2>Facilities</h2>
      <ul class="checklist">{"".join(f"<li>{f}</li>" for f in facilities)}</ul>
    </section>

    <section>
      <h2>Departments at {h['name']}</h2>
      <div class="grid grid--auto-220">{"".join(dept_card(d, base) for d in departments)}</div>
    </section>

    <section>
      <h2>Insurance Accepted</h2>
      <div class="pill-list">{"".join(f"<span>{i}</span>" for i in h['insurance'])}</div>
    </section>

    <section>
      <h2>Location</h2>
      <div class="map-placeholder"><i data-lucide="map"></i></div>
      <p class="muted" style="margin-top:10px;">{h['area']}, {CITIES[h['city']]['name']} — replace this with a real Google Maps iframe.</p>
    </section>

    <section>
      <h2>FAQs</h2>
      {faq_block([
          ("Does the hospital offer 24×7 emergency services?","Yes. Emergency care is available round-the-clock, including ambulance support."),
          (f"How many beds does {h['name']} have?", f"{h['beds']} beds across general wards, private rooms and the {h['icu']}-bed ICU."),
          ("What insurance is accepted?", f"Major insurers including {', '.join(h['insurance'][:3])} and others. Please confirm with the hospital insurance desk."),
          ("Where is the hospital located?", f"{h['area']}, {CITIES[h['city']]['name']}.")
      ])}
    </section>
  </div>

  <aside class="profile-sidebar">
    <div class="sb-card">
      <h4>Contact</h4>
      <div class="row"><span>Hospital</span><strong>{h['name']}</strong></div>
      <div class="row"><span>Phone</span><strong>{h['phone']}</strong></div>
      <div class="row"><span>Area</span><strong>{h['area']}</strong></div>
      <div class="row"><span>City</span><strong>{CITIES[h['city']]['name']}</strong></div>
      <a class="btn btn--primary btn--block mt-2" href="tel:<?= preg_replace('/[^0-9+]/','',$PHONE_CALL) ?>"><i data-lucide="phone"></i>Call</a>
      <a class="btn btn--ghost btn--block mt-2" href="tel:<?= preg_replace('/[^0-9+]/','',$PHONE_EMERGENCY) ?>"><i data-lucide="siren"></i>Emergency</a>
    </div>
    <div class="sb-card">
      <h4>Quick links</h4>
      <div style="display:flex;flex-direction:column;gap:6px;">
        <a href="../{h['city']}/index.php">Hospitals in {CITIES[h['city']]['name']}</a>
        <a href="../doctor/index.php">All doctors</a>
        <a href="../department/index.php">All departments</a>
      </div>
    </div>
  </aside>
</div>

<section class="section">
  <div class="section__head"><h2>Doctors at the hospital</h2></div>
  <div class="grid grid--4">{"".join(doctor_card(d, base) for d in related_docs)}</div>
</section>

<section class="section">
  <div class="section__head"><h2>Nearby hospitals</h2></div>
  <div class="grid grid--3">{"".join(hospital_card(hh, base) for hh in nearby)}</div>
</section>
</div>
"""
    content = page_header(php_vars, base="../", active_nav="hospitals", extra_schema=extra_schema) + body + page_footer(base="../")
    write(f"hospital/{h['slug']}.php", content)

def gen_department_page(slug):
    name, icon, treatments, conditions = DEPARTMENTS[slug]
    base = "../"
    docs = doctors_for_dept(slug)[:8]
    hosps = hospitals_for_dept(slug)[:6]
    title = f"{name} Doctors & Hospitals in Chandigarh, Mohali, Panchkula"
    desc = f"Find the best {name.lower()} doctors and hospitals across the tricity. Verified profiles, treatments, conditions and patient reviews."
    php_vars = render_meta(title, desc, f"/department/{slug}.php") + f"\n  $breadcrumbs = [['label'=>'Home','url'=>'{SITE_URL}/'], ['label'=>'Departments','url'=>'{SITE_URL}/department/index.php'], ['label'=>{repr(name)}]];"
    body = f"""
<section class="hero" style="padding:60px 0 80px;">
  <div class="container">
    <span class="eyebrow"><i data-lucide="{icon}" style="width:14px;height:14px;vertical-align:middle"></i> Department</span>
    <h1>{name} <em>across the tricity</em></h1>
    <p class="hero__lead">{name} doctors and hospitals across Chandigarh, Mohali and Panchkula — covering {len(treatments)} key procedures and {len(conditions)} common conditions.</p>
  </div>
</section>

<section class="section">
  <div class="container">
    <div class="section__head"><div><span class="eyebrow">Procedures</span><h2>Treatments offered</h2></div></div>
    <div class="pill-list">{"".join(f"<span>{t}</span>" for t in treatments)}</div>
  </div>
</section>

<section class="section section--soft">
  <div class="container">
    <div class="section__head"><div><span class="eyebrow">Conditions</span><h2>What we treat</h2></div></div>
    <div class="pill-list">{"".join(f"<span>{c}</span>" for c in conditions)}</div>
  </div>
</section>

<section class="section">
  <div class="container">
    <div class="section__head"><div><span class="eyebrow">Top rated</span><h2>{name} doctors</h2></div><a class="btn btn--ghost" href="{base}doctor/index.php">All doctors <i data-lucide="arrow-right"></i></a></div>
    <div class="grid grid--4">{"".join(doctor_card(d, base) for d in docs)}</div>
  </div>
</section>

<section class="section section--soft">
  <div class="container">
    <div class="section__head"><div><span class="eyebrow">Featured</span><h2>{name} hospitals</h2></div><a class="btn btn--ghost" href="{base}hospital/index.php">All hospitals <i data-lucide="arrow-right"></i></a></div>
    <div class="grid grid--3">{"".join(hospital_card(h, base) for h in hosps)}</div>
  </div>
</section>

<section class="section">
  <div class="container" style="max-width:880px;">
    <div class="section__head"><div><span class="eyebrow">FAQ</span><h2>About {name}</h2></div></div>
    {faq_block([
        (f"When should I consult a {name.lower()} doctor?", f"Consult a {name.lower()} specialist if you experience any of: {', '.join(conditions[:3])}. Early consultation usually improves outcomes."),
        (f"What treatments are offered under {name}?", f"Common procedures include {', '.join(treatments[:3])} and others depending on the diagnosis."),
        ("How do I book an appointment?", "Click any doctor card above and use the Call or WhatsApp button on their profile to book.")
    ])}
  </div>
</section>

<section class="section section--tight"><div class="container"><div class="cta-band"><div><h2>Need help choosing a {name.lower()} specialist?</h2><p>Our care coordinator can suggest the right doctor and hospital based on your needs.</p></div><div class="btns"><a class="btn btn--light btn--lg" href="tel:<?= preg_replace('/[^0-9+]/','',$PHONE_CALL) ?>"><i data-lucide="phone"></i>Call now</a></div></div></div></section>
"""
    content = page_header(php_vars, base="../", active_nav="departments") + body + page_footer(base="../")
    write(f"department/{slug}.php", content)

def gen_department_index():
    base = "../"
    php_vars = render_meta("All Medical Departments — TriCity Health Directory",
                           "Browse 38+ medical departments across Chandigarh, Mohali and Panchkula.",
                           "/department/index.php") + f"\n  $breadcrumbs = [['label'=>'Home','url'=>'{SITE_URL}/'], ['label'=>'Departments']];"
    cards = "".join(dept_card(s, base) for s in DEPARTMENTS.keys())
    body = f"""
<section class="hero" style="padding:60px 0;"><div class="container"><span class="eyebrow">Browse</span><h1>All medical departments</h1><p class="hero__lead">38 medical specialities served by verified hospitals and doctors across the tricity.</p></div></section>
<section class="section"><div class="container"><div class="grid grid--auto-280">{cards}</div></div></section>
"""
    content = page_header(php_vars, base="../", active_nav="departments") + body + page_footer(base="../")
    write("department/index.php", content)

def gen_doctor_index():
    base = "../"
    php_vars = render_meta("All Doctors — TriCity Health Directory",
                           "Browse all verified doctors across Chandigarh, Mohali and Panchkula.",
                           "/doctor/index.php") + f"\n  $breadcrumbs = [['label'=>'Home','url'=>'{SITE_URL}/'], ['label'=>'Doctors']];"
    cards = "".join(doctor_card(d, base) for d in DOCTORS)
    body = f"""
<section class="hero" style="padding:60px 0;"><div class="container"><span class="eyebrow">Top rated · {len(DOCTORS)} profiles</span><h1>All doctors</h1><p class="hero__lead">Verified specialists across the tricity. Search, compare, and book.</p></div></section>
<section class="section"><div class="container"><p class="muted" style="margin-bottom:24px;">Showing all <strong>{len(DOCTORS)}</strong> doctors across Chandigarh, Mohali and Panchkula.</p><div class="grid grid--4">{cards}</div></div></section>
"""
    content = page_header(php_vars, base="../", active_nav="doctors") + body + page_footer(base="../")
    write("doctor/index.php", content)

def gen_hospital_index():
    base = "../"
    php_vars = render_meta("All Hospitals — TriCity Health Directory",
                           "Browse all multi-speciality hospitals across Chandigarh, Mohali and Panchkula.",
                           "/hospital/index.php") + f"\n  $breadcrumbs = [['label'=>'Home','url'=>'{SITE_URL}/'], ['label'=>'Hospitals']];"
    cards = "".join(hospital_card(h, base) for h in HOSPITALS)
    body = f"""
<section class="hero" style="padding:60px 0;"><div class="container"><span class="eyebrow">Featured</span><h1>All hospitals</h1><p class="hero__lead">{len(HOSPITALS)} verified multi-speciality hospitals across the tricity.</p></div></section>
<section class="section"><div class="container"><p class="muted" style="margin-bottom:24px;">Showing all <strong>{len(HOSPITALS)}</strong> hospitals across Chandigarh, Mohali and Panchkula.</p><div class="grid grid--3">{cards}</div></div></section>
"""
    content = page_header(php_vars, base="../", active_nav="hospitals") + body + page_footer(base="../")
    write("hospital/index.php", content)

def gen_city_page(city):
    base = "../"
    info = CITIES[city]
    docs = doctors_for_city(city)[:8]
    hosps = hospitals_for_city(city)[:6]
    title = f"Doctors & Hospitals in {info['name']} — TriCity Health Directory"
    desc = f"Find the best hospitals, doctors and departments in {info['name']}. {info['blurb']}"
    php_vars = render_meta(title, desc, f"/{city}/index.php") + f"\n  $breadcrumbs = [['label'=>'Home','url'=>'{SITE_URL}/'], ['label'=>{repr(info['name'])}]];"

    treatments = ["Cardiac surgery","Joint replacement","Cancer care","Maternity","Dental implants","LASIK","Dialysis","IVF"]
    
    body = f"""
<section class="hero">
  <div class="container">
    <span class="eyebrow"><i data-lucide="map-pin" style="width:14px;height:14px;vertical-align:middle"></i> {info['name']}</span>
    <h1>Healthcare in <em>{info['name']}</em></h1>
    <p class="hero__lead">{info['blurb']}</p>
    <div class="hero__chips" style="margin-top:18px;">
      <a class="chip" href="best-cardiologist.php"><i data-lucide="heart-pulse"></i>Best Cardiologist</a>
      <a class="chip" href="best-orthopedic-doctor.php"><i data-lucide="bone"></i>Best Orthopedic</a>
      <a class="chip" href="best-gynecologist.php"><i data-lucide="venus"></i>Best Gynecologist</a>
      <a class="chip" href="best-pediatrician.php"><i data-lucide="baby"></i>Best Pediatrician</a>
      <a class="chip" href="best-dermatologist.php"><i data-lucide="hand"></i>Best Dermatologist</a>
    </div>
  </div>
</section>

<section class="section">
  <div class="container">
    <div class="section__head"><div><span class="eyebrow">Hospitals</span><h2>Top hospitals in {info['name']}</h2></div><a class="btn btn--ghost" href="{base}hospital/index.php">All hospitals <i data-lucide="arrow-right"></i></a></div>
    <div class="grid grid--3">{"".join(hospital_card(h, base) for h in hosps)}</div>
  </div>
</section>

<section class="section section--soft">
  <div class="container">
    <div class="section__head"><div><span class="eyebrow">Doctors</span><h2>Top doctors in {info['name']}</h2></div><a class="btn btn--ghost" href="{base}doctor/index.php">All doctors <i data-lucide="arrow-right"></i></a></div>
    <div class="grid grid--4">{"".join(doctor_card(d, base) for d in docs)}</div>
  </div>
</section>

<section class="section">
  <div class="container">
    <div class="section__head"><div><span class="eyebrow">Specialities</span><h2>Departments in {info['name']}</h2></div></div>
    <div class="grid grid--auto-220">{"".join(dept_card(s, base) for s in list(DEPARTMENTS.keys())[:12])}</div>
  </div>
</section>

<section class="section section--soft">
  <div class="container">
    <div class="section__head"><div><span class="eyebrow">Popular</span><h2>Popular treatments</h2></div></div>
    <div class="pill-list">{"".join(f"<span>{t}</span>" for t in treatments)}</div>
  </div>
</section>

<section class="section">
  <div class="container">
    <div class="section__head"><div><span class="eyebrow">Location</span><h2>Where we serve</h2></div></div>
    <div class="map-placeholder"><i data-lucide="map"></i></div>
  </div>
</section>

<section class="section">
  <div class="container" style="max-width:880px;">
    <div class="section__head"><div><span class="eyebrow">FAQ</span><h2>About healthcare in {info['name']}</h2></div></div>
    {faq_block([
        (f"Which is the biggest hospital in {info['name']}?", f"{info['name']} has multiple multi-speciality hospitals — see our featured list above for the top options."),
        (f"How do I find a specialist in {info['name']}?", "Use the search at the top of the page or filter by department on the doctors page."),
        ("Are tele-consultations available?", "Yes. Many doctors listed offer online consultations — look for the badge on their profile.")
    ])}
  </div>
</section>

<section class="section section--tight"><div class="container"><div class="cta-band"><div><h2>Care coordinator in {info['name']}</h2><p>Get help selecting the right hospital or doctor — completely free.</p></div><div class="btns"><a class="btn btn--light btn--lg" href="tel:<?= preg_replace('/[^0-9+]/','',$PHONE_CALL) ?>"><i data-lucide="phone"></i>Call now</a></div></div></div></section>
"""
    content = page_header(php_vars, base="../", active_nav="cities") + body + page_footer(base="../")
    write(f"{city}/index.php", content)

def gen_city_dept_page(city, dept_slug, label, label_hosp):
    info = CITIES[city]
    dept_name = DEPARTMENTS[dept_slug][0]
    base = "../"
    docs = doctors_for_dept(dept_slug, city)[:6] or doctors_for_city(city)[:6]
    hosps = hospitals_for_dept(dept_slug, city)[:6] or hospitals_for_city(city)[:6]
    
    title = f"Best {label} in {info['name']} 2026 — Top {dept_name} Doctors"
    desc = f"Top-rated {label.lower()} in {info['name']}. Compare verified {dept_name.lower()} doctors and hospitals — qualification, experience and patient reviews."
    php_vars = render_meta(title, desc, f"/{city}/best-{slugify(label)}.php") + f"\n  $breadcrumbs = [['label'=>'Home','url'=>'{SITE_URL}/'], ['label'=>{repr(info['name'])},'url'=>'{SITE_URL}/{city}/index.php'], ['label'=>{repr('Best '+label)}]];"
    body = f"""
<section class="hero" style="padding:60px 0 80px;">
  <div class="container">
    <span class="eyebrow"><i data-lucide="award" style="width:14px;height:14px;vertical-align:middle"></i> Editor's picks · 2026</span>
    <h1>Best <em>{label}</em> in {info['name']}</h1>
    <p class="hero__lead">A curated list of top-rated {dept_name.lower()} doctors and hospitals in {info['name']}. Verified credentials, real patient reviews and instant contact options.</p>
  </div>
</section>

<section class="section">
  <div class="container">
    <div class="section__head"><div><span class="eyebrow">Top rated</span><h2>Featured {label.lower()}s in {info['name']}</h2></div></div>
    <div class="grid grid--4">{"".join(doctor_card(d, base) for d in docs)}</div>
  </div>
</section>

<section class="section section--soft">
  <div class="container">
    <div class="section__head"><div><span class="eyebrow">Hospitals</span><h2>Best {label_hosp.lower()}s in {info['name']}</h2></div></div>
    <div class="grid grid--3">{"".join(hospital_card(h, base) for h in hosps)}</div>
  </div>
</section>

<section class="section">
  <div class="container" style="max-width:880px;">
    <div class="section__head"><div><span class="eyebrow">Editorial</span><h2>How we pick the best {label.lower()}</h2></div></div>
    <p>Our editorial team evaluates each doctor and hospital on the following criteria:</p>
    <ul class="checklist">
      <li>Verified medical credentials and active registration</li>
      <li>Years of relevant clinical experience</li>
      <li>Patient ratings (≥ 4.4/5 average over 12 months)</li>
      <li>Hospital affiliation and infrastructure (ICU, OT, emergency)</li>
      <li>Procedure volumes for sub-speciality cases</li>
      <li>Transparent pricing and patient communication</li>
    </ul>
  </div>
</section>

<section class="section section--soft">
  <div class="container" style="max-width:880px;">
    <div class="section__head"><div><span class="eyebrow">FAQ</span><h2>Frequently asked</h2></div></div>
    {faq_block([
        (f"Who is the best {label.lower()} in {info['name']}?", f"Several excellent {label.lower()}s practice in {info['name']}. Our curated list above ranks top doctors by reviews, experience and hospital affiliation."),
        (f"What is the typical consultation fee for a {label.lower()} in {info['name']}?", "Consultation fees range from ₹400 to ₹1,500 depending on the doctor's seniority and hospital."),
        (f"Do {label.lower()}s in {info['name']}offer online consultation?", "Yes, many do. Look for the 'Online consult' indicator on each doctor profile.")
    ])}
  </div>
</section>

<section class="section section--tight"><div class="container"><div class="cta-band"><div><h2>Talk to a care coordinator</h2><p>Get matched to the right {dept_name.lower()} specialist in {info['name']}.</p></div><div class="btns"><a class="btn btn--light btn--lg" href="tel:<?= preg_replace('/[^0-9+]/','',$PHONE_CALL) ?>"><i data-lucide="phone"></i>Call now</a><a class="btn btn--ghost btn--lg" style="color:#fff;border-color:rgba(255,255,255,.4);" href="https://wa.me/<?= preg_replace('/[^0-9]/','',$PHONE_WHATSAPP) ?>"><i data-lucide="message-circle"></i>WhatsApp</a></div></div></div></section>
"""
    content = page_header(php_vars, base="../", active_nav="cities") + body + page_footer(base="../")
    write(f"{city}/best-{slugify(label)}.php", content)

def gen_simple_page(slug, title, body_html):
    php_vars = render_meta(f"{title} — TriCity Health Directory", title, f"/{slug}.php") + f"\n  $breadcrumbs = [['label'=>'Home','url'=>'{SITE_URL}/'], ['label'=>{repr(title)}]];"
    body = f"""
<section class="hero" style="padding:60px 0;"><div class="container"><h1>{title}</h1></div></section>
<section class="section"><div class="container" style="max-width:820px;">{body_html}</div></section>
"""
    content = page_header(php_vars, base="", active_nav="") + body + page_footer(base="")
    write(f"{slug}.php", content)

def gen_sitemap():
    urls = [SITE_URL + "/"]
    for c in CITIES.keys(): urls.append(f"{SITE_URL}/{c}/index.php")
    for d in DEPARTMENTS.keys(): urls.append(f"{SITE_URL}/department/{d}.php")
    urls.append(f"{SITE_URL}/department/index.php")
    urls.append(f"{SITE_URL}/doctor/index.php")
    urls.append(f"{SITE_URL}/hospital/index.php")
    for h in HOSPITALS: urls.append(f"{SITE_URL}/hospital/{h['slug']}.php")
    for d in DOCTORS:   urls.append(f"{SITE_URL}/doctor/{d['slug']}.php")
    for c in CITIES.keys():
        for (dept_slug, label, _) in CITY_DEPT_SEO:
            urls.append(f"{SITE_URL}/{c}/best-{slugify(label)}.php")
    for s in ["about","contact","privacy","terms"]:
        urls.append(f"{SITE_URL}/{s}.php")
    items = "\n".join(f"  <url><loc>{u}</loc><changefreq>weekly</changefreq><priority>0.7</priority></url>" for u in urls)
    xml = f"""<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{items}
</urlset>
"""
    write("sitemap.xml", xml)

# -------- RUN --------
def run():
    # Departments
    for slug in DEPARTMENTS.keys():
        gen_department_page(slug)
    gen_department_index()

    # Hospitals
    for h in HOSPITALS:
        gen_hospital_page(h)
    gen_hospital_index()

    # Doctors
    for d in DOCTORS:
        gen_doctor_page(d)
    gen_doctor_index()

    # Cities
    for c in CITIES.keys():
        gen_city_page(c)

    # City x Department SEO pages
    for c in CITIES.keys():
        for (dept_slug, label, label_hosp) in CITY_DEPT_SEO:
            gen_city_dept_page(c, dept_slug, label, label_hosp)

    # Static info pages
    gen_simple_page("about", "About TriCity Health Directory",
        "<p>TriCity Health Directory is an independent, editorial directory of doctors, hospitals and medical departments serving Chandigarh, Mohali and Panchkula. Our team verifies credentials, hospital affiliations and patient feedback before listing any profile.</p>"
        "<p>We do not charge patients for searches, listings or appointment requests. Profiles are re-verified every 90 days to keep information accurate.</p>")
    gen_simple_page("contact", "Contact",
        "<p>Have feedback or a profile update? We respond within 24 hours on business days.</p>"
        "<p><strong>Email:</strong> <a href='mailto:<?= $EMAIL ?>'><?= $EMAIL ?></a><br>"
        "<strong>Call:</strong> <a href='tel:<?= preg_replace(\"/[^0-9+]/\",\"\",$PHONE_CALL) ?>'><?= $PHONE_CALL ?></a><br>"
        "<strong>WhatsApp:</strong> <a href='https://wa.me/<?= preg_replace(\"/[^0-9]/\",\"\",$PHONE_WHATSAPP) ?>'><?= $PHONE_WHATSAPP ?></a></p>")
    gen_simple_page("privacy", "Privacy Policy",
        "<p>We do not sell or share your personal information. Search queries are stored anonymously to improve the directory.</p>"
        "<p>For appointment requests we share only the contact details you submit with the chosen clinic. Read the full policy on this page.</p>")
    gen_simple_page("terms", "Terms of Service",
        "<p>TriCity Health Directory is an information-only platform. Always verify clinical details directly with the hospital or doctor before treatment.</p>"
        "<p>We make reasonable efforts to keep listings accurate but cannot guarantee real-time availability or pricing.</p>")

    # Sitemap
    gen_sitemap()

    # Output summary
    print("Hospitals:", len(HOSPITALS))
    print("Doctors:",   len(DOCTORS))
    print("Departments:", len(DEPARTMENTS))
    print("City x Department pages:", len(CITIES) * len(CITY_DEPT_SEO))

if __name__ == "__main__":
    run()
