#!/usr/bin/env nu
# sync-all-pages.nu
# Reads source_html from each project's index.ncl and syncs FTL files.
#
# Usage:
#   nu scripts/sync/sync-all-pages.nu
#   nu scripts/sync/sync-all-pages.nu --only ontoref
#   nu scripts/sync/sync-all-pages.nu --dry-run

const PROJECTS_DIR = "site/content/projects/en"
const I18N_EN = "site/i18n/locales/en/pages"
const I18N_ES = "site/i18n/locales/es/pages"

def main [
    --only: string = "",    # Sync a single project by id
    --dry-run               # Preview without writing
] {
    # Collect all project dirs that have an index.ncl with source_html
    let project_dirs = (ls $PROJECTS_DIR | where type == dir | get name)

    let projects = $project_dirs | each { |dir|
        let ncl_path = $"($dir)/index.ncl"
        if not ($ncl_path | path exists) { return null }

        let content = open $ncl_path
        let id_match = $content | parse --regex 'id\s*=\s*"(?P<id>[^"]+)"' | first | get id? | default ""
        let src_match = $content | parse --regex 'source_html\s*=\s*"(?P<path>[^"]+)"' | first | get path? | default ""

        if $src_match == "" { return null }
        { id: $id_match, source_html: $src_match }
    } | compact | where { |p| $p != null and $p.id != "" and $p.source_html != "" }

    if ($projects | length) == 0 {
        print "No projects with source_html found."
        return
    }

    let targets = if $only != "" {
        $projects | where id == $only
    } else {
        $projects
    }

    if ($targets | length) == 0 {
        print $"Project '($only)' not found or has no source_html."
        return
    }

    for p in $targets {
        print $"\n── ($p.id) ──"

        let out_en = $"($I18N_EN)/($p.id).ftl"
        let out_es = $"($I18N_ES)/($p.id).ftl"

        if $dry_run {
            nu scripts/sync/sync-page-ftl.nu --html $p.source_html --out-en $out_en --out-es $out_es --dry-run
        } else {
            nu scripts/sync/sync-page-ftl.nu --html $p.source_html --out-en $out_en --out-es $out_es
        }
    }

    print "\n✓ Done"
}
