#!/usr/bin/env python3
"""
Build the Singapore (/sg) cinematic page from the KL cinematic page.

    python3 tools/apply_sg.py resources/views/cinematic/home.blade.php resources/views/cinematic/sg.blade.php

Same mechanism as tools/apply_hk.py / apply_ae.py (the founder's): every replacement is anchored
on text in the KL template and the script prints OK or MISS per rule. Nothing in the KL file is
modified. Written 2026-10-15 for the chooser's Singapore panel, which had no page of its own.

Every figure is REAL, read from wk's Singapore rows on 2026-10-15 (see the cinematic-site readMe):
  - ELTA, 2-bedroom 614 sq ft (layout_analyses): S$1,580,500 = S$2,574 psf; predicted market value
    S$1,579,822 (S$2,573 psf), transacted S$2,572 psf, verdict FAIR PRICE (0.04% above value).
  - Rent: URA rental contracts, District 05, 2 bedrooms, 550-700 sq ft, Sep 2025 on: 600 contracts,
    P10 / median / P90 = S$3,700 / 4,000 / 4,400.
  - District 05 private sales, median net psf by year: 2022 1,697 · 2023 1,899 · 2024 1,901 ·
    2025 2,200 · 2026 2,178.  47 published estates within 2 km of ELTA.
  - Both laptop maps are the REAL map (Mapbox light-v11 via the Static Images API, as the product)
    with pins at real coordinates: the nine District 05 launches with their "from" prices, and the
    12 estates with the most recorded sales within 2 km of ELTA, coloured by recorded PSF.
  - The four Discover cards are real launches in District 05 with their real "from" prices and our
    stored artist's impressions; developers are named only where the project's own material does.
  - Loan: Singapore's prefill (config/markets.php SG): 75%, 3.0%, 30 years -> S$4,998 / month.
    Maintenance S$370 / month is an ESTIMATE (S$0.60 psf; the catalogue has no fee for ELTA) and is
    labelled as one. 50% down -> S$3,332 / month -> +S$298. Equity at 3% yearly growth.
"""
import re, sys
SRC, DST = sys.argv[1], sys.argv[2]
A = '/cinematic/sg/assets/'          # SG-only assets (films, photos, phone shot)
t = open(SRC, encoding='utf-8').read()
log = []
def lit(name, old, new, n=None):
    global t
    c = t.count(old)
    if c == 0 or (n is not None and c != n): log.append(f'MISS  {name}  (found {c})'); return
    t = t.replace(old, new); log.append(f'OK    {name}  x{c}')
def rx(name, pat, new, flags=re.S):
    global t
    t2, c = re.subn(pat, new, t, flags=flags)
    if c == 0: log.append(f'MISS  {name}'); return
    t = t2; log.append(f'OK    {name}  x{c}')


# ---------------------------------------------------------------- 0. films
# The three key-handover shots, re-made with Singapore outside the window (Seedance 2.5 video edit
# of the KL films). Part B keeps KL's Hong Kong evening: the owner is abroad, "even from Hong Kong".
rx('film connect',  r"(['\"])(?:[^'\"]*connect-film[^'\"]*\.(?:mp4|webm)|/_blob/b46358d1b5df530dbc2e89ea78231311)\1", f"'{A}connect-film-sg.mp4'")
rx('film beyond A', r"(['\"])(?:[^'\"]*beyond-a[^'\"]*\.(?:mp4|webm)|/_blob/bbe80baddf80a4adbd91560fbf398a76)\1", f"'{A}beyond-a-sg.mp4'")
rx('film beyond B', r"(['\"])(?:[^'\"]*beyond-b[^'\"]*\.(?:mp4|webm)|/_blob/e9b1ccf77703bdcdbb12bb39ec1fa10e)\1", f"'{A}beyond-b-sg.mp4'")
# The laptop-opening film and its still: KL's, with the screen replaced by the Singapore Discover
# screen (rendered from this page's own HTML, tracked onto the film's screen frame by frame).
rx('lid-open film', r"(['\"])(?:[^'\"]*lid-open[^'\"]*\.(?:mp4|webm)|/_blob/f7fce263f7693ec20805da670f461739)\1", f"'{A}lid-open.mp4'")
rx('lap_open still', r'(<img class="lapopen"[^>]*src=")[^"]*(")', r'\g<1>' + A + r'lap_open.webp\g<2>')
rx('header comment', r'^\{\{--.*?--\}\}', '{{-- PropertyLab cinematic page, Singapore (/sg). Generated from cinematic/home.blade.php by tools/apply_sg.py. Do not hand-edit; rebuild instead. --}}', flags=0)

# ---------------------------------------------------------------- 1. page meta
lit('title', '<title>PropertyLab AI · Cross-border property, decided on evidence</title>', '<title>PropertyLab AI · Singapore property, decided on evidence</title>')

# ---------------------------------------------------------------- 2. Discover laptop screen
rx('country tabs', r'<span>&#127469;&#127472; Hong Kong <em>\d+</em></span><span class="on">&#127474;&#127486; Malaysia <em>67</em></span><span>&#127462;&#127466; United Arab Emirates <em>951</em></span>',
   '<span class="on">&#127480;&#127468; Singapore <em>103</em></span><span>&#127474;&#127486; Malaysia <em>67</em></span><span>&#127469;&#127472; Hong Kong <em>319</em></span><span>&#127462;&#127466; UAE <em>951</em></span>')
lit('price chips', '<span>Under RM 500k</span><span>RM 500k - 900k</span><span>Over RM 900k</span>', '<span>Under S$1.5M</span><span>S$1.5M - 2.5M</span><span>Over S$2.5M</span>')
rx('quality chips -> districts', r'<div><b>Project quality</b>.*?</div></div>',
   '<div><b>District</b> <small>District 05</small><div class="d-chips q"><span class="on">Clementi</span><span>one-north</span><span>Science Park</span><span>Queenstown</span></div></div>')
rx('assumptions', r'<p class="d-assume">.*?</p>',
   '<p class="d-assume"><b>Cashflow assumptions</b> &middot; Default terms: 75% loan &middot; 3% interest &middot; 30 years &middot; maintenance S$0.60/sf (est.). <b>Change &rarr;</b></p>')
rx('project count', r'67 projects &middot; showing 1-24', '103 projects &middot; showing 1-24')
CARD = lambda img,tags,loc,name,dev,price,extra: (f'<div class="d-card"><div class="d-img" style="background-image:url({A}{img})"><u class="tl">Singapore</u>{tags}</div>\n'
        f'              <small>{loc}</small><b>{name}</b><small>{dev}</small><small class="f">From</small><strong>{price}</strong>{extra}</div>\n')
cards = ('<div class="d-grid">\n' +
  CARD('sg-card-1.jpg','<u class="tr">&#9733; Featured</u><u class="br">New Launch</u>','Clementi, District 05','ELTA','by MCL Land &amp; CSC Land','S$1,284,000 - 4,079,000',
       '\n              <div class="d-tags"><i class="g">Fairly priced</i><i class="g">Yield 3.0%</i><i class="r">Cashflow -S$1,368/mo</i></div>') +
  CARD('sg-card-2.jpg','<u class="br">New Launch</u>','one-north, District 05','Bloomsbury Residences','New launch, TOP 2029','S$1,398,500','') +
  CARD('sg-card-3.jpg','<u class="br">New Launch</u>','Science Park, District 05','LyndenWoods','by CapitaLand Development','S$1,499,000','') +
  CARD('sg-card-4.jpg','<u class="br">New Launch</u>','Queenstown, District 05','Hudson Place Residences','New launch, TOP 2029','S$1,663,500','') +
  '          </div>\n          <div class="d-map"')
rx('discover cards', r'<div class="d-grid">.*?</div>\s*<div class="d-map"', cards)
rx('discover map labels', r"\[\['(?:Selayang|Dubai Marina)'.*?\]\]\.forEach",
   "[['Bukit Timah',470,150,15],['Clementi',170,240,20],['Holland Village',470,270,14],['one-north',290,360,16],['Dover',220,370,14],['Queenstown',520,400,16],['Science Park',330,490,14],['West Coast',100,470,14],['Pasir Panjang',250,580,15]].forEach")
rx('discover map prices', r"\[\['(?:MYR 2\.7M|AED 29\.9M)'.*?\]\]\.forEach",
   "[['S$1.28M',190,265],['S$1.40M',360,300],['S$1.50M',310,430],['S$1.66M',430,350],['S$1.93M',400,240],['S$1.78M',540,370],['S$1.85M',150,330],['S$2.1M',480,190],['S$1.62M',240,520],['S$2.4M',560,470]].forEach")

# ---------------------------------------------------------------- 3. Evidence laptop screen
rx('EV_BARS', r'const EV_BARS=\[.*?\];',
   'const EV_BARS=[["This project",2574,\'sub\'],["2022",1697],["2023",1899],["2024",1901],["2025",2200],["2026",2178]];')
lit('chart title', 'Median asking PSF, nearest projects', 'District 05 PSF by year, private sales')
lit('banner name', '<div><i>&#10016;</i>BINASTRA<br>COCHRANE</div>', '<div><i>&#10016;</i>ELTA<br>CLEMENTI</div>')
lit('banner count', '<div class="count">5 / 11</div>', '<div class="count">1 / 22</div>')
lit('banner meta', '<span class="pill">Preleased</span><small>Serviced Apartment</small><h3>Binastra Cochrane</h3><div class="loc">Kuala Lumpur, Cochrane by Binastra Group</div>',
    '<span class="pill">New launch</span><small>Condominium</small><h3>ELTA</h3><div class="loc">Clementi, Singapore, by MCL Land &amp; CSC Land</div>')
lit('banner price', '<div class="price">RM 655,000 to RM 1,250,000</div>', '<div class="price">S$1,284,000 to S$4,079,000</div>')
rx('unit chips', r'<div class="ev-units">Current unit.*?</div>\s*</div>',
   '<div class="ev-units">Current unit\n            <div class="ev-chip">1 Bed<small>506 sq ft, S$1,284,000</small></div>\n            <div class="ev-chip on">2 Bed<small>614 sq ft, S$1,580,500</small></div>\n            <div class="ev-chip">3 Bed<small>975 sq ft, S$2,525,000</small></div>\n          </div>')
lit('DMA unit label', '<span style="font-weight:400;color:#7b86a0;font-size:13px">Type A</span>', '<span style="font-weight:400;color:#7b86a0;font-size:13px">2 Bed, 614 sq ft</span>')
rx('KPIs', r'<div class="ev-kpis">.*?</div>\s*<div class="ev-row">',
   '<div class="ev-kpis">\n              <div class="ev-kpi ev-fade"><div class="l">YOUR PRICE (NEW)</div><div class="v" data-count="1580500" data-pre="S$">S$1,580,500</div><div class="s">2 bed, 614 sq ft, S$2,574 psf</div></div>\n'
   '              <div class="ev-kpi pred ev-fade"><div class="l">PREDICTED MARKET VALUE</div><div class="v" data-count="1579822" data-pre="S$">S$1,579,822</div><div class="s">S$2,573 psf from nearby sales</div></div>\n'
   '              <div class="ev-kpi fair ev-fade"><div class="l">FAIR PRICE CHECK</div><div class="v">Fairly priced</div><div class="s">0.04% above predicted value</div></div>\n            </div>\n            <div class="ev-row">')
lit('comparables chip', '29 properties', '47 estates')
lit('comparables count', 'from the nearest 13 projects', 'from 47 estates within 2 km')
rx('evidence map labels', r'\[\["Kuala Lumpur",150,120,15\].*?\]\],', '[["Clementi",150,120,15],["Dover",290,250,12],["one-north",345,95,12],["West Coast",120,215,11]],')
lit('chart currency', '>RM ${t.toLocaleString', '>S$${t.toLocaleString')
lit('bar colours', 'v>2000?C.r:v>1500?C.o:v>1200?C.y:C.g', 'v>2400?C.r:v>2100?C.o:v>1800?C.y:C.g')
lit('predicted line', 'Y(1002)', 'Y(2573)')
lit('predicted label', "'Predicted RM 1,002'", "'Predicted S$2,573'")
lit('stats asking', '<div>Median asking PSF<b data-count="1082" data-pre="RM ">RM 1,082</b></div>', '<div>This unit PSF<b data-count="2574" data-pre="S$">S$2,574</b></div>')
lit('stats transacted', '<div>Median transacted PSF<b data-count="1057" data-pre="RM ">RM 1,057</b></div>', '<div>Median transacted PSF<b data-count="2572" data-pre="S$">S$2,572</b></div>')
lit('stats predicted', '<div class="pr">Predicted PSF<b data-count="1002" data-pre="RM ">RM 1,002</b></div>', '<div class="pr">Predicted PSF<b data-count="2573" data-pre="S$">S$2,573</b></div>')

# ---------------------------------------------------------------- 4. Evidence phone
lit('phone project', '<div><b>Binastra Cochrane</b><small>Type A, 2 bed, 649 sqft</small></div><div class="pr">RM 649,620</div>',
    '<div><b>ELTA</b><small>2 bed, 614 sq ft</small></div><div class="pr">S$1.58M</div>')
lit('phone price', '<b data-count="649620" data-pre="RM ">RM 649,620</b></div><div class="ps">649 sqft, RM 1,001 psf</div>',
    '<b data-count="1580500" data-pre="S$">S$1,580,500</b></div><div class="ps">614 sq ft, S$2,574 psf</div>')
lit('phone predicted value', '<b data-count="650298" data-pre="RM ">RM 650,298</b>', '<b data-count="1579822" data-pre="S$">S$1,579,822</b>')
lit('phone predicted psf', 'RM 1,002 psf from', 'S$2,573 psf from')
lit('phone fair', '<div class="pc fair"><div class="pl">Fair price check</div><div class="pv"><b>Fairly priced</b></div><div class="ps">0.1% below predicted value</div></div>',
    '<div class="pc fair"><div class="pl">Fair price check</div><div class="pv"><b>Fairly priced</b></div><div class="ps">0.04% above predicted value</div></div>')
lit('phone stats', '<span>Asking<b data-count="1082" data-pre="RM ">RM 1,082</b></span><span>Transacted<b data-count="1057" data-pre="RM ">RM 1,057</b></span><span class="p">Predicted<b data-count="1002" data-pre="RM ">RM 1,002</b></span>',
    '<span>This unit<b data-count="2574" data-pre="S$">S$2,574</b></span><span>Transacted<b data-count="2572" data-pre="S$">S$2,572</b></span><span class="p">Predicted<b data-count="2573" data-pre="S$">S$2,573</b></span>')
lit('phone rent', '<b data-count="2450" data-pre="RM ">RM 2,450</b><span>/ month</span>', '<b data-count="4000" data-pre="S$">S$4,000</b><span>/ month</span>')
lit('phone rent range', '<span>RM 1,700</span><span>median of 10 nearby units</span><span>RM 3,900</span>', '<span>S$3,700</span><span>median of 600 nearby 2-bed rentals</span><span>S$4,400</span>')
lit('rent marker', '(2450-1700)/(3900-1700)', '(4000-3700)/(4400-3700)')
lit('phone instalment', '<b data-count="2589" data-pre="RM ">RM 2,589</b><span>/ month</span></div>\n          <div class="ps">90% loan, 4.0% interest, 35 years</div>',
    '<b data-count="4998" data-pre="S$">S$4,998</b><span>/ month</span></div>\n          <div class="ps">75% loan, 3.0% interest, 30 years</div>')
rx('phone cashflow', r'<div class="wf"><span>Rental</span>.*?<div class="net"><span>Net cashflow</span><b data-count="366"[^<]*</b>',
   '<div class="wf"><span>Rental</span><i><b class="wb in" data-w=".8"></b></i><em>+4,000</em></div>\n          <div class="wf"><span>Instalment</span><i><b class="wb out" data-w="1"></b></i><em>&minus;4,998</em></div>\n          <div class="wf"><span>Maintenance</span><i><b class="wb mt" data-w=".074"></b></i><em>&minus;370</em></div>\n          <div class="net"><span>Net cashflow</span><b data-count="1368" data-pre="&minus;S$" data-post=" / mo">&minus;S$1,368 / mo</b>')
lit('roi ring text', 'id="roiTxt">8.1%</text>', 'id="roiTxt">3.0%</text>')
lit('roi ring label', '>ROI p.a.</text>', '>Gross yield</text>')
lit('roi ring anim', "251.3*(1-.81*ra));$('roiTxt').textContent=(8.1*ra).toFixed(1)+'%'", "251.3*(1-.30*ra));$('roiTxt').textContent=(3.0*ra).toFixed(1)+'%'")
lit('roi stats', '<div>Projected ROI<b data-count="8.1" data-dec="1" data-post="%">8.1%</b></div><div>Gross yield<b data-count="4.5" data-dec="1" data-post="%">4.5%</b></div><div>Break-even rent<b data-count="2816" data-pre="RM ">RM 2,816</b></div>',
    '<div>Equity in 30 yrs<b data-count="3.84" data-dec="2" data-pre="S$" data-post="M">S$3.84M</b></div><div>Gross yield<b data-count="3.0" data-dec="1" data-post="%">3.0%</b></div><div>Break-even rent<b data-count="5368" data-pre="S$">S$5,368</b></div>')

# ---------------------------------------------------------------- 5. AI + Plan
lit('question', 'Is Binastra Cochrane Type A a good buy for me?', 'Is the ELTA 2-bed a good buy for me?')
lit('conversation list', '<div class="ai-conv on">Binastra Cochrane, Type A</div><div class="ai-conv">Rental yield vs cashflow</div><div class="ai-conv">Dual-key studios in KL</div><div class="ai-conv">Dubai vs Kuala Lumpur</div>',
    '<div class="ai-conv on">ELTA, 2 Bed</div><div class="ai-conv">Rental yield vs cashflow</div><div class="ai-conv">Clementi new launches</div><div class="ai-conv">Singapore vs Kuala Lumpur</div>')
lit('chat header', '<div class="ai-ch">Binastra Cochrane, Type A<div class="ai-ctx"><span>Market value</span><span>Cashflow</span><span>13 comparables</span></div></div>',
    '<div class="ai-ch">ELTA, 2 Bed<div class="ai-ctx"><span>Market value</span><span>Cashflow</span><span>47 estates</span></div></div>')
lit('answer 1', 'data-t="Short answer: the price is fair, but as a whole-unit rental it costs you about RM 366 a month to hold."',
    'data-t="Short answer: the price is fair, but as a rental with a 75% loan it costs you about S$1,368 a month to hold."')
lit('chips desktop', '<div class="ai-chip ok">Fair price<b>0.1% below market</b></div><div class="ai-chip neg">Cashflow<b>&minus;RM 366 / mo</b></div><div class="ai-chip roi">Projected ROI<b>8.1% p.a.</b></div>',
    '<div class="ai-chip ok">Fair price<b>0.04% above market</b></div><div class="ai-chip neg">Cashflow<b>&minus;S$1,368 / mo</b></div><div class="ai-chip roi">Gross yield<b>3.0% p.a.</b></div>')
lit('answer 3', 'data-t="1. Rent by room. At about RM 2,900 a month in total, cashflow turns positive at +RM 84."',
    'data-t="1. Put 50% down. The instalment drops to about S$3,332 and cashflow turns positive at +S$298."')
lit('answer 4', 'data-t="2. Hold for the long run. At 3.5% yearly growth, your equity reaches about RM 2.17 million in 35 years."',
    'data-t="2. Hold for the long run. At 3% yearly growth, your equity reaches about S$3.84 million in 30 years."')
lit('actions', '<span>Compare with Type B</span>', '<span>Compare with the 3-bed</span>')
lit('phone answer 1', 'data-t="The price is fair, but as a whole-unit rental it costs about RM 366 a month to hold."',
    'data-t="The price is fair, but as a rental with a 75% loan it costs about S$1,368 a month to hold."')
lit('phone chips', '<div class="ai-chip ok">Fair price<b>0.1% below</b></div><div class="ai-chip neg">Cashflow<b>&minus;RM 366</b></div><div class="ai-chip roi">ROI<b>8.1%</b></div>',
    '<div class="ai-chip ok">Fair price<b>0.04% above</b></div><div class="ai-chip neg">Cashflow<b>&minus;S$1,368</b></div><div class="ai-chip roi">Yield<b>3.0%</b></div>')
lit('phone answer 2', 'data-t="Rent by room at about RM 2,900 and cashflow turns positive. Hold 35 years and your equity grows to about RM 2.17 million."',
    'data-t="Put 50% down and cashflow turns positive. Hold 30 years and your equity grows to about S$3.84 million."')
lit('phone plan bar', '&#8592;</span>Binastra Cochrane<span', '&#8592;</span>ELTA<span')
lit('phone equity value', '<div class="eqv"><small>RM</small><span id="eqVal">2,165,567</span></div><div class="eqs">Final equity after 35 years</div>',
    '<div class="eqv"><small>S$</small><span id="eqVal">3,836,288</span></div><div class="eqs">Final equity after 30 years</div>')
lit('phone milestones', '<div class="mil"><div>Year 10<b>RM 425,914</b></div><div>Year 20<b>RM 942,632</b></div><div>Loan paid off<b>Year 35</b></div></div>',
    '<div class="mil"><div>Year 10<b>S$1,222,940</b></div><div>Year 20<b>S$2,337,000</b></div><div>Loan paid off<b>Year 30</b></div></div>')
lit('duo check', 'data-t="Here is my price check on Type A."', 'data-t="Here is my price check on the 2-bed."')
lit('duo verdict', '<span class="pill">&#10003; Fairly priced</span><small>0.1% below market value</small>', '<span class="pill">&#10003; Fairly priced</span><small>0.04% above market value</small>')
lit('duo gauge', '<span><i class="dm"></i>Market RM 650,298</span><span><i class="dy"></i>You RM 649,620</span>', '<span><i class="dm"></i>Market S$1,579,822</span><span><i class="dy"></i>You S$1,580,500</span>')
lit('duo gauge marks', "cov.querySelector('.mm').style.left=(51.5*g)+'%'; cov.querySelector('.my').style.left=(48.1*g)+'%';",
    "cov.querySelector('.mm').style.left=(49.6*g)+'%'; cov.querySelector('.my').style.left=(50.4*g)+'%';")
lit('duo tiles', '<div class="tile neg"><small>Whole unit</small><b>&minus;RM 366</b><small>/ month</small></div><div class="tile pos"><small>Rent by room</small><b>+RM 84</b><small>/ month</small></div>',
    '<div class="tile neg"><small>75% loan</small><b>&minus;S$1,368</b><small>/ month</small></div><div class="tile pos"><small>50% down</small><b>+S$298</b><small>/ month</small></div>')
lit('plan header', '<span>Binastra Cochrane, Type A</span>', '<span>ELTA, 2 Bed</span>')
lit('plan big', '<small>RM</small><span class="eqv">2,165,567</span>', '<small>S$</small><span class="eqv">3,836,288</span>')
lit('plan sub', '<div class="sub">after 35 years at 3.5% yearly growth</div>', '<div class="sub">after 30 years at 3% yearly growth</div>')
rx('plan table', r'<div class="card amort"><div class="lbl">Amortization schedule.*?</tbody></table></div>',
   '<div class="card amort"><div class="lbl">Amortization schedule <span class="lt">75% loan, S$4,998 / month</span></div>\n      <table><thead><tr><th>Year</th><th>Value</th><th>Loan balance</th><th>Equity</th></tr></thead><tbody>'
   '<tr><td>Year 1</td><td>1,627,915</td><td>1,160,627</td><td class="e">467,288</td></tr>'
   '<tr><td>Year 5</td><td>1,832,233</td><td>1,053,874</td><td class="e">778,359</td></tr>'
   '<tr><td>Year 10</td><td>2,124,060</td><td>901,120</td><td class="e">1,222,940</td></tr>'
   '<tr><td>Year 20</td><td>2,854,559</td><td>517,559</td><td class="e">2,337,000</td></tr>'
   '<tr><td>Year 30</td><td>3,836,288</td><td>0</td><td class="e">3,836,288</td></tr></tbody></table></div>')
lit('plan cashflow line', '<span>Rent by room: RM 2,900 rent, RM 2,589 instalment, RM 227 maintenance</span><b class="netv">+RM 84 / mo</b>',
    '<span>With 50% down: S$4,000 rent, S$3,332 instalment, S$370 maintenance (est.)</span><b class="netv">+S$298 / mo</b>')
lit('plan summary pills', '<div class="ca sum"><span class="pill ok">&#10003; Fairly priced</span><span class="pill neg">&minus;RM 366 / mo as a whole unit</span></div>',
    '<div class="ca sum"><span class="pill ok">&#10003; Fairly priced</span><span class="pill neg">&minus;S$1,368 / mo with a 75% loan</span></div>')
lit('plan intro', 'data-t="Here is your plan. Renting by room is the better setup for this unit."', 'data-t="Here is your plan. A 50% down payment is the better setup for this unit."')
rx('plan compare', r'<div class="rc cmp">.*?</div></div>\s*<div class="rc eqm">',
   '<div class="rc cmp"><div class="opt"><span>75% loan</span><b class="neg">&minus;S$1,368</b><small>per month, rent S$4,000</small><i><em data-w=".8" style="background:#e5484d"></em></i></div>\n'
   '          <div class="opt best"><span>50% down <u>Plan</u></span><b class="pos">+S$298</b><small>per month, rent S$4,000</small><i><em data-w="1" style="background:#3cc27a"></em></i></div></div>\n        <div class="rc eqm">')
lit('plan equity', '<small>Equity in 35 years</small><b>RM 2.17M</b><span class="x">&#8599; 3.3x your purchase price</span>',
    '<small>Equity in 30 years</small><b>S$3.84M</b><span class="x">&#8599; 2.4x your purchase price</span>')
lit('plan slot', '<small>Book a viewing of the Type A show unit</small>', '<small>Book a viewing of the ELTA show flat</small>')
lit('plan source', 'Based on 13 comparables, 10 nearby rentals and your budget', 'Based on 47 estates, 600 nearby rentals and your budget')
lit('plan mobile label', '<div class="lbl">Equity in 35 years</div>', '<div class="lbl">Equity in 30 years</div>')
rx('plan mobile table', r'<table><thead><tr><th>Year</th><th>Loan</th><th>Equity</th></tr></thead><tbody>.*?</tbody></table>',
   '<table><thead><tr><th>Year</th><th>Loan</th><th>Equity</th></tr></thead><tbody><tr><td>Yr 1</td><td>1,160,627</td><td class="e">467,288</td></tr><tr><td>Yr 10</td><td>901,120</td><td class="e">1,222,940</td></tr><tr><td>Yr 20</td><td>517,559</td><td class="e">2,337,000</td></tr><tr><td>Yr 30</td><td>0</td><td class="e">3,836,288</td></tr></tbody></table>')
lit('plan mobile text', 'data-t="Rent by room and you keep about RM 84 a month. Your equity grows to about RM 2.17 million in 35 years. Book a viewing?"',
    'data-t="Put 50% down and you keep about S$298 a month. Your equity grows to about S$3.84 million in 30 years. Book a viewing?"')
EQ = [[0,395125,1185375],[1,467288,1160627],[2,541627,1135126],[3,618206,1108849],[4,697093,1081773],[5,778359,1053874],[6,862074,1025126],[7,948312,995503],[8,1037150,964980],[9,1128666,933528],[10,1222940,901120],[11,1320056,867726],[12,1420099,833316],[13,1523158,797859],[14,1629324,761324],[15,1738689,723678],[16,1851352,684887],[17,1967410,644916],[18,2086966,603729],[19,2210127,561289],[20,2337000,517559],[21,2467697,472499],[22,2602334,426067],[23,2741029,378224],[24,2883905,328926],[25,3031088,278128],[26,3182708,225785],[27,3338898,171849],[28,3499796,116274],[29,3665544,59008],[30,3836288,0]]
rx('EQ data', r'const EQ=\[\[0, 64962, 584658\].*?\]\];', 'const EQ=' + str(EQ).replace(' ', '') + ';')
lit('EQ scale', 'YM=3000000,X=t=>X0+(X1-X0)*t/35', 'YM=4000000,X=t=>X0+(X1-X0)*t/30')
lit('EQ ticks', "[0,1e6,2e6,3e6].forEach(v=>s+=", "[0,1e6,2e6,3e6,4e6].forEach(v=>s+=")
lit('EQ tick label', "${v?'RM '+v/1e6+'M':'RM 0'}", "${v?'S$'+v/1e6+'M':'S$0'}")
lit('EQ year labels', '[1,10,20,35].forEach(t=>s+=', '[1,10,20,30].forEach(t=>s+=')
lit('EQ end x', '${X(35)}', '${X(30)}')
lit('EQ tip', 'Y(EQ[35][1])', 'Y(EQ[30][1])')
lit('EQ counter', 'Math.round(2165567*e)', 'Math.round(3836288*e)')
lit('netv counter', '`+RM ${Math.round(84*ease(k2(.45,.62)))} / mo`', '`+S$${Math.round(298*ease(k2(.45,.62)))} / mo`')
lit('full plan title', '<h3>Your plan for Binastra Cochrane, Type A</h3><p>Prepared by PropertyLab AI from 13 comparables, nearby rents and your budget.</p>',
    '<h3>Your plan for ELTA, 2 Bed</h3><p>Prepared by PropertyLab AI from 47 estates, nearby rents and your budget.</p>')
lit('full plan sub', 'Projected equity after 35 years at 3.5% yearly growth', 'Projected equity after 30 years at 3% yearly growth')
rx('full plan cashflow', r'<div class="lbl">Monthly cashflow, rented by room</div>.*?<div class="net"><span>Net cashflow</span><b class="netv">\+RM 84 / mo</b></div>',
   '<div class="lbl">Monthly cashflow, with 50% down</div>\n        <div class="wf"><span>Rent</span><i><b data-w="1" style="background:#3cc27a"></b></i><em>+4,000</em></div>\n        <div class="wf"><span>Instalment</span><i><b data-w=".833" style="background:#2f6bff"></b></i><em>&minus;3,332</em></div>\n        <div class="wf"><span>Maintenance (est.)</span><i><b data-w=".093" style="background:#9aa6bf"></b></i><em>&minus;370</em></div>\n        <div class="net"><span>Net cashflow</span><b class="netv">+S$298 / mo</b></div>')
lit('full plan step 1', 'Book a viewing<small>Binastra Cochrane show unit, Kuala Lumpur</small>', 'Book a viewing<small>ELTA show flat, Clementi</small>')
lit('full plan step 2', 'Get mortgage pre-approval<small>90% loan at about 4.0%, 35 years</small>', 'Get mortgage pre-approval<small>50% loan at about 3.0%, 30 years</small>')
lit('full plan step 3', '<small>Room-rental setup and tenancy plan</small>', '<small>Tenancy plan and leasing setup</small>')

# ---------------------------------------------------------------- 6. Connect + Beyond copy and film captions
lit('connect step 3', 'Offer, booking fee, loan approval, SPA and handover, followed step by step in your PropertyLab app.',
    'Option to purchase, loan approval, S&amp;P agreement and handover, followed step by step in your PropertyLab app.')
lit('film captions', "const CAPS=['Booking your viewing with a verified partner agent','Meet your licensed partner agent, on the ground in Kuala Lumpur','Viewing confirmed: Saturday 14:00, Binastra Cochrane','Offer, loan, SPA and keys, tracked to the end'];",
    "const CAPS=['Booking your viewing with a verified partner agent','Meet your licensed partner agent, on the ground in Singapore','Viewing confirmed: Saturday 14:00, ELTA show flat','Option, loan, S&P and keys, tracked to the end'];")
lit('beyond film comment', '(film, two parts: KL then Hong Kong)', '(film, two parts: Singapore then Hong Kong)')

# ---------------------------------------------------------------- 7. App section phone + footer
rx('app phone shot', r'(<img class="ph4-shot" src=")[^"]*(" alt=")[^"]*(")', r'\g<1>' + A + r'sg-phone-shot.jpg\g<2>PropertyLab app, Analyze: ELTA, Singapore\g<3>')
lit('app chip 1', '<div class="ph3-chip c1"><i class="dot g"></i>Fairly priced<small>0.1% below market</small></div>', '<div class="ph3-chip c1"><i class="dot g"></i>Fairly priced<small>0.04% above market</small></div>')
lit('app chip 2', '<div class="ph3-chip c2"><b>8.1%</b><small>Projected ROI</small></div>', '<div class="ph3-chip c2"><b>3.0%</b><small>Gross yield</small></div>')
lit('fallback map unit', 'Your unit · KL', 'Your unit · Clementi')
lit('fallback map labels', "[['Kuala Lumpur',200,196,12],['Cheras',230,150,9],['Ampang',240,60,9]]", "[['Clementi',200,196,12],['Dover',230,150,9],['one-north',240,60,9]]")
lit('footer note', 'Viewings and transactions are handled by licensed partners. Kuala Lumpur · Hong Kong.', 'Viewings and transactions are handled by licensed partners. Singapore · Kuala Lumpur · Hong Kong · Dubai.')
lit('cursor comment', 'cursor clicks Binastra Cochrane', 'cursor clicks ELTA')
rx('discover link', r'<a class="textlink" href="[^"]*">Open Analyze Property</a>', '<a class="textlink" href="/analyze-property/new-projects?country=sg">Open Analyze Property</a>')

# ---------------------------------------------------------------- 7b. real maps (2026-10-15)
# Owner: "why the property map show in MacBook is not real one?" The KL page draws its maps in
# code (a warped street grid, invented parks, invented prices). Singapore's two maps are the real
# Mapbox light-v11 map the product uses (Static Images API, loaded live with the product's public
# token, Mapbox + OpenStreetMap attribution kept on the image), with the pins drawn over it at
# the projects' real coordinates (Web Mercator, 512 px tiles), sized to the boxes' real CSS size (613×625, 341×360). Discover = the nine District 05
# launches and their real "from" prices; Evidence = the 12 estates with the most recorded sales
# within 2 km of ELTA (of the 47), coloured by recorded PSF on the heat map's Singapore bands.
DISC_MAP = r"""/* Discover map: the real map (Mapbox light-v11, as in the product) + the real District 05 launches */
window.mbProj=function(lon0,lat0,z,W,H){const S=512*Math.pow(2,z),mx=l=>(l+180)/360*S,my=a=>{const s=Math.sin(a*Math.PI/180);return(.5-Math.log((1+s)/(1-s))/(4*Math.PI))*S;},cx=mx(lon0),cy=my(lat0);return(lon,lat)=>[W/2+mx(lon)-cx,H/2+my(lat)-cy];};
window.mbUrl=(lon0,lat0,z,W,H)=>`https://api.mapbox.com/styles/v1/mapbox/light-v11/static/${lon0},${lat0},${z},0/${W}x${H}@2x?access_token=${window.MBT}`;
(function(){
  const el=$('dMap'),W=613,H=625,LON=103.7742,LAT=1.3002,Z=13.05,P=mbProj(LON,LAT,Z,W,H);
  /* name, lat, lng, from-price, bubble offset (to keep close neighbours apart) */
  const L=[['ELTA',1.3075564,103.7676132,'S$1.28M',0,-22],['Bloomsbury Residences',1.2944424,103.7951287,'S$1.40M',-4,-26],['Hudson Place Residences',1.2930060,103.7952159,'S$1.66M',-4,26],
    ['LyndenWoods',1.2913268,103.7882609,'S$1.50M',-44,20],['Blossoms by the Park',1.3043941,103.7892982,'S$1.39M',-40,-22],['The Hill @ One-North',1.3029726,103.7902462,'S$1.93M',44,6],
    ['Faber Residence',1.3225129,103.7531711,'S$1.39M',0,-22],['Terra Hill',1.2779499,103.7933283,'S$1.88M',-52,-12],['The Hillshore',1.2867412,103.7801491,'S$1.74M',-36,22]];
  let s=`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="xMidYMid slice" style="position:absolute;inset:0;width:100%;height:100%">`;
  L.forEach(([n,la,lo,t,dx,dy])=>{const[x,y]=P(lo,la);s+=`<g transform="translate(${x.toFixed(1)} ${y.toFixed(1)})"><title>${n}</title><line x1="0" y1="0" x2="${dx}" y2="${dy}" stroke="#0f1b33" stroke-opacity=".35" stroke-width="1.2"/><circle r="5" fill="#2f6bff" stroke="#fff" stroke-width="2"/><g transform="translate(${dx} ${dy})"><rect x="-38" y="-13" width="76" height="26" rx="8" fill="#fff" stroke="#dfe5f0"/><text y="4.5" font-size="13" font-weight="700" text-anchor="middle" fill="#0f1b33" font-family="Inter,system-ui,sans-serif">${t}</text></g></g>`;});
  el.style.background=`#eef1ec ${window.MBT?`url(${mbUrl(LON,LAT,Z,W,H)})`:''} center/cover no-repeat`;
  el.insertAdjacentHTML('afterbegin',s+'</svg>');
})();"""
rx('discover map: real', r"/\* Discover map: drawn live.*?\n\}\)\(\);", lambda m: DISC_MAP)
EV_MAP = r"""/* Comparison map: the real map around ELTA + the estates with the most recorded sales within 2 km */
  function mapImg(el,W,H,lon0,lat0,z,pins){
    const P=mbProj(lon0,lat0,z,W,H);
    el.style.background=`#eef1ea ${window.MBT?`url(${mbUrl(lon0,lat0,z,W,H)})`:''} center/cover no-repeat`;
    el.innerHTML=`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="xMidYMid slice"><g class="pins"></g></svg>`;
    const g=el.querySelector('.pins');
    return pins.map(([name,lat,lon,c,big])=>{const k=big?1.35:1,[x,y]=P(lon,lat);
      const p=document.createElementNS('http://www.w3.org/2000/svg','g');
      p.innerHTML=`<title>${name}</title><ellipse cx="0" cy="1" rx="${5*k}" ry="${2*k}" fill="rgba(15,27,51,.25)"/><path transform="scale(${k})" d="M0 0 C-7 -10 -10 -14 -10 -19 A10 10 0 1 1 10 -19 C10 -14 7 -10 0 0Z" fill="${c}" stroke="#fff" stroke-width="1.6"/><circle cy="${-19*k}" r="${3.6*k}" fill="#fff"/>`;
      g.appendChild(p);return{el:p,x,y};});
  }
  /* recorded PSF (URA, S$): < 1,500 green · 1,500-1,800 yellow · 1,800-2,100 orange · above red */
  const psfC=v=>v<1500?C.g:v<1800?C.y:v<2100?C.o:C.r;
  const mapPins=mapImg($('evMap'),341,360,103.7700,1.3080,12.75,[
    ...[['Parc Clematis',1.3164,103.75962,2011],['Whistler Grand',1.31961,103.75433,1872],['Clavon',1.30851,103.76709,2010],['The Trilinq',1.31863,103.76114,1704],['The Clement Canopy',1.30668,103.76854,1863],
    ['Dover Parkview',1.30609,103.78435,1367.5],['Seahill',1.29891,103.76445,1547],['Heritage View',1.30442,103.78428,1553],['Pine Grove',1.31815,103.77514,1054.5],['Blue Horizon',1.29768,103.7651,1333],
    ['The Parc Condominium',1.31088,103.76274,1816],['Varsity Park Condominium',1.29446,103.76892,1425]].map(([n,la,lo,v])=>[n,la,lo,psfC(v)]),
    ['ELTA',1.3075564,103.7676132,C.b,1]]); /* ELTA last: drawn on top of its two neighbours */"""
rx('evidence map: real', r"const mapPins=mapSVG\(\$\('evMap'\).*?\]\]\);", lambda m: EV_MAP)
rx('project count: District 05', r'103 projects &middot; showing 1-24', '9 projects &middot; showing 1-9')

# ---------------------------------------------------------------- 8. style overrides
STYLE = ('<style id="sg-overrides">\n'
 f'.ev-banner{{background:#1b1d24 url({A}sg-banner.jpg) center 35%/cover}}\n'
 '.ev-banner .p1,.ev-banner .p2,.ev-banner .p3,.ev-banner .p4{visibility:hidden}\n'
 f'.ev-thumbs{{background:url({A}sg-thumbs.jpg) left center/auto 100% no-repeat}}\n'
 f'.a-ph{{background-image:url({A}sg-card-1.jpg)}}\n'
 '</style>\n')
# The page is one @verbatim block; the Mapbox public token is printed in a short break out of it.
TOKEN = "@endverbatim\n<script>window.MBT=@json((string) config('services.mapbox.token'));</script>\n@verbatim\n"
lit('style block', '</head>', STYLE + TOKEN + '</head>', n=1)

open(DST, 'w', encoding='utf-8').write(t)
print('\n'.join(log))
miss = sum(l.startswith('MISS') for l in log)
print(f'\n{len(log)-miss} OK, {miss} MISS  ->  {DST}')
sys.exit(1 if miss else 0)
