#!/usr/bin/env python3
"""
Generate Astro pages from the static clone.

Approach: Astro supports placing .html files directly under src/pages/ — building
copies them to dist/ verbatim (output identical to the original site). We copy
every cloned page's HTML into src/pages/ preserving its route, and copy all
non-HTML assets into public/ (Astro copies public/ -> dist/).

This gives a real Astro project (astro build -> dist/) whose output matches the
original website exactly, while all assets are self-hosted and URLs relative.

Run from repo root.
"""
import os, shutil

ROOT = os.path.dirname(os.path.abspath(__file__))
SOURCE = os.path.join(ROOT, "site")
PAGES = os.path.join(ROOT, "src", "pages")
ASSETS = os.path.join(ROOT, "public")
BUILD = os.path.join(ROOT, "dist")

# remove sample astro page
sample = os.path.join(PAGES, "index.astro")
if os.path.exists(sample):
    os.remove(sample)

def main():
    os.makedirs(PAGES, exist_ok=True)
    os.makedirs(ASSETS, exist_ok=True)

    # 1. Copy all assets (non-index.html) into public/ preserving structure
    copied = 0
    for dp, dns, fns in os.walk(SOURCE):
        for fn in fns:
            if fn == "index.html":
                continue
            src = os.path.join(dp, fn)
            rel = os.path.relpath(src, SOURCE)
            dst = os.path.join(ASSETS, rel)
            os.makedirs(os.path.dirname(dst), exist_ok=True)
            shutil.copy2(src, dst)
            copied += 1
    print(f"Copied {copied} asset files into public/")

    # 2. Copy each page's HTML into src/pages/ preserving route as .html
    gen = 0
    for dp, dns, fns in os.walk(SOURCE):
        if "index.html" not in fns:
            continue
        html_src = os.path.join(dp, "index.html")
        rel_dir = os.path.relpath(os.path.dirname(html_src), SOURCE)
        if rel_dir == ".":
            page_rel = "index.html"
        else:
            page_rel = rel_dir + ".html"     # e.g. catalog/item/X.html, catalog.html
        page_dst = os.path.join(PAGES, page_rel)
        os.makedirs(os.path.dirname(page_dst), exist_ok=True)
        shutil.copy2(html_src, page_dst)
        gen += 1
        print(f"  {page_rel}")
    print(f"\nGenerated {gen} html pages under src/pages/")

if __name__ == "__main__":
    main()
