#!/usr/bin/env python3
"""Builds the complete Surch portal:
   index.html      candidate site (jobs, profile, dashboard, messages, company & policy pages)
   employers.html  employer site (landing, plans, registration) + the signed-in hiring app
Both pages share data through SurchBridge (surch-shared/bridge.js), so a candidate applying on
index.html shows up on the employer's board in employers.html, and every employer action
(interview, document request, message, offer, rejection) reaches the candidate."""
import os, subprocess, shutil
HERE = os.path.dirname(os.path.abspath(__file__))
HOME = os.path.dirname(HERE)
subprocess.run(["python3", os.path.join(HOME, "surch-shared", "empdemo", "sync.py")], check=True)
subprocess.run(["python3", "build.py"], cwd=os.path.join(HOME, "surch-candidate"), check=True, stdout=subprocess.DEVNULL)
subprocess.run(["python3", "-W", "ignore", "build.py"], cwd=os.path.join(HOME, "surch-site"), check=True, stdout=subprocess.DEVNULL)
shutil.copy(os.path.join(HOME, "surch-candidate", "preview.html"), os.path.join(HERE, "index.html"))
app = open(os.path.join(HOME, "apptrack.html"), encoding="utf-8").read()
HEAD = ('<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n'
        '<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">\n'
        '<meta name="description" content="Surch for employers: post jobs, find talent, track applicants and manage your workforce.">\n'
        '<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Crect width=%2232%22 height=%2232%22 rx=%228%22 fill=%22%235b2a86%22/%3E%3Ctext x=%2216%22 y=%2222%22 text-anchor=%22middle%22 font-family=%22Arial%22 font-weight=%22700%22 font-size=%2218%22 fill=%22%23fff%22%3Es%3C/text%3E%3C/svg%3E">\n')
open(os.path.join(HERE, "employers.html"), "w", encoding="utf-8").write(HEAD + app.replace("<title>Surch</title>", "<title>Surch for Employers</title>", 1))
# showcase images for the employer homepage storyboards, served beside employers.html
SC_SRC = os.path.join(HOME, "surch-site", "assets", "scenes"); SC_DST = os.path.join(HERE, "scenes")
shutil.rmtree(SC_DST, ignore_errors=True); os.makedirs(SC_DST)
for f in os.listdir(SC_SRC):
    if f.endswith(".webp"): shutil.copy(os.path.join(SC_SRC, f), SC_DST)
CS_SRC = os.path.join(HOME, "surch-candidate", "assets", "cstory")   # candidate hero storyboard frames
for f in os.listdir(CS_SRC):
    if f.endswith(".webp"): shutil.copy(os.path.join(CS_SRC, f), SC_DST)
# ---- text-size accessibility: scale every font size from one setting, add the control and homepage card ----
import re
TS = os.path.join(HOME, "surch-shared", "textsize")
def _r(n): return open(os.path.join(TS, n), encoding="utf-8").read()
_CLAMP = re.compile(r'font-size:\s*(clamp\((?:[^()]|\([^()]*\))*\))')
_FS = re.compile(r'font-size:\s*(\d*\.?\d+)px')
_LH = re.compile(r'line-height:\s*(\d*\.?\d+)px')
_FONT = re.compile(r'(font:\s*(?:[a-z0-9-]+\s+)*?)(\d*\.?\d+)px')
def scale_text(h):
    h = _CLAMP.sub(lambda m: f'font-size:calc({m.group(1)}*var(--ts,1))', h)
    h = _FS.sub(lambda m: f'font-size:calc({m.group(1)}px*var(--ts,1))', h)
    h = _LH.sub(lambda m: f'line-height:calc({m.group(1)}px*var(--ts,1))', h)
    h = _FONT.sub(lambda m: f'{m.group(1)}calc({m.group(2)}px*var(--ts,1))', h)
    return h
def add_textsize(name, card_before):
    fp = os.path.join(HERE, name); h = open(fp, encoding="utf-8").read()
    assert h.count(card_before) == 1, (name, card_before)
    h = h.replace(card_before, _r("card.html") + "\n" + card_before, 1)
    h = h.replace("<head>", "<head>\n<style>\n" + _r("card.css") + "\n</style>", 1)
    h = scale_text(h)
    h = h.replace("<head>", "<head>\n<script>" + _r("head.js").strip() + "</script>", 1)
    tail = h[-400:]; k = tail.rfind("</body>")
    i = len(h) - 400 + k if k >= 0 else len(h)   # only the document's real closing tag, never one inside a JS string
    h = h[:i] + "<style>\n" + _r("ts.css") + "\n</style>\n<script>\n" + _r("ts.js") + "\n</script>\n" + h[i:]
    open(fp, "w", encoding="utf-8").write(h)
add_textsize("index.html", '<section class="lp-sec cd-score')
add_textsize("employers.html", '<section class="lp-sec lp-pricing"')
for f in ("index.html", "employers.html"):
    print(f, f"{os.path.getsize(os.path.join(HERE, f))/1024:.0f} KB")
# ---- standalone builds: fix cross-folder links and storyboard frames (see fix_standalone.py) ----
subprocess.run(["python3", os.path.join(HERE, "fix_standalone.py")], check=True)
