#!/usr/bin/env python3
"""Makes the standalone builds work when opened straight from their own folders.

The combined portal (surch-portal/index.html + employers.html) keeps both sites side by side,
so its links use "employers.html" and "index.html#/...". The standalone builds live in separate
folders, where those names point at the wrong file or at nothing:

  surch-candidate/index.html  ->  employer links must go to ../surch-site/
  surch-site/*.html            ->  candidate links (index.html#/...) must go to ../surch-candidate/
                                   and the employer storyboards need surch-site/scenes/
"""
import os, re, shutil
HOME = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CAND = os.path.join(HOME, "surch-candidate")
SITE = os.path.join(HOME, "surch-site")

def patch(path, subs):
    s = open(path, encoding="utf-8").read(); n = 0
    for pat, rep in subs:
        s, k = re.subn(pat, rep, s); n += k
    open(path, "w", encoding="utf-8").write(s)
    return n

# 1. candidate standalone: employer links go to the employer standalone pages
cand_subs = [
    (r'employers\.html#/login', '../surch-site/login.html'),
    (r'employers\.html#/plans', '../surch-site/plans.html'),
    (r'employers\.html#/register', '../surch-site/register.html'),
    (r'(["\'])employers\.html(["\'])', r'\1../surch-site/index.html\2'),
]
n = patch(os.path.join(CAND, "index.html"), cand_subs)
for f in os.listdir(os.path.join(CAND, "js")):
    if f.endswith(".js"): n += patch(os.path.join(CAND, "js", f), cand_subs)
print("candidate standalone links fixed:", n)

# 2. employer standalone: candidate links go to the candidate site, storyboard frames sit beside the pages
site_subs = [(r'(["\'])index\.html#/', r'\1../surch-candidate/index.html#/')]
n = 0
for f in os.listdir(SITE):
    if f.endswith(".html"): n += patch(os.path.join(SITE, f), site_subs)
print("employer standalone links fixed:", n)
src, dst = os.path.join(SITE, "assets", "scenes"), os.path.join(SITE, "scenes")
shutil.rmtree(dst, ignore_errors=True); os.makedirs(dst)
k = 0
for f in os.listdir(src):
    if f.endswith(".webp"): shutil.copy(os.path.join(src, f), dst); k += 1
print("employer storyboard frames copied:", k)
