#!/usr/bin/env bash
# Generates per-domain DYNAMIC ReDoc loader pages for all API services.
#
# Each generated doc/<service>.html is a small loader that:
#   - loads branding.js (per-domain config keyed by window.location.hostname)
#   - renders ReDoc from /openapi/openapi.php?...&file=<service>.yaml
#     so the spec's info.title (brand) and server fullUrl are injected per domain.
# This replaces the old static pre-rendered bundles that baked the "ITT" brand in.
set -euo pipefail

SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
REDOC_DIR="$ROOT_DIR/doc"
REDOC_VERSION="v2.5.1"
# Cache-busting token for the branding.js reference so a CDN/browser never serves a
# stale copy after a redeploy (a new query string is a new URL, not the cached one).
ASSET_VERSION="$(date +%s)"

mkdir -p "$REDOC_DIR"

echo "🚀 Generating dynamic documentation loaders..."

# Generate one loader page.
#   $1 = output file name (e.g. flight.html)
#   $2 = spec file served via openapi.php (e.g. flight.yaml)
#   $3 = service display name (e.g. Flight)
build_service() {
    local output_name="$1"
    local spec_file="$2"
    local service_name="$3"
    local out="$REDOC_DIR/$output_name"
    echo "📦 Generating $output_name (service: $service_name, spec: $spec_file)..."

    cat > "$out" <<'EOF'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Loading documentation…</title>
    <link id="favicon" rel="icon" href="/doc/public/itt.ico">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Outfit:wght@500;700&display=swap" rel="stylesheet">
    <style>
        body { margin: 0; padding: 0; }
        .itt-top-header { position: fixed; top: 0; left: 0; width: 260px; height: 60px; background: rgba(15, 23, 42, 0.9); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); display: flex; align-items: center; padding: 0 20px; z-index: 10000; border-bottom: 1px solid rgba(255, 255, 255, 0.1); box-sizing: border-box; }
        .back-btn { color: #f8fafc; text-decoration: none; font-family: "Inter", sans-serif; font-weight: 600; font-size: 13px; display: flex; align-items: center; gap: 8px; transition: all 0.3s ease; background: rgba(255, 255, 255, 0.05); padding: 6px 12px; border-radius: 6px; border: 1px solid rgba(255, 255, 255, 0.1); }
        .back-btn:hover { background: rgba(255, 255, 255, 0.1); transform: translateX(-3px); border-color: #38bdf8; color: #38bdf8; }
        .back-btn .arrow { font-size: 16px; }
        .menu-content, [data-role="redoc-menu"] { margin-top: 60px !important; }
        .menu-content { top: 60px !important; height: calc(100vh - 60px) !important; }
        @media (max-width: 768px) { .itt-top-header { width: 100%; padding: 0 16px; } #redoc-container { margin-top: 60px !important; } }
    </style>
    <script src="branding.js?v=__ASSET_VERSION__"></script>
</head>
<body>
    <div class="itt-top-header"><a href="index.html" class="back-btn" title="Back to Portal"><span class="arrow">&larr;</span><span class="text">Back to Portal</span></a></div>
    <div id="redoc-container"></div>
    <script src="https://cdn.redocly.com/redoc/__REDOC_VERSION__/bundles/redoc.standalone.js"></script>
    <script>
        (function () {
            var host = window.location.hostname;
            var cfg = (window.BRANDING && (window.BRANDING.domains[host] || window.BRANDING.default)) || {};
            var brand = cfg.clientName || "ITT";
            var service = "__SERVICE_NAME__";
            var file = "__SERVICE_FILE__";
            document.title = brand + " " + service + " API";
            // Per-domain favicon (from branding.js).
            if (cfg.favicon) {
                var favLink = document.getElementById("favicon") || document.querySelector('link[rel~="icon"]');
                if (!favLink) { favLink = document.createElement("link"); favLink.id = "favicon"; favLink.rel = "icon"; document.head.appendChild(favLink); }
                favLink.href = cfg.favicon;
            }
            var specUrl = "/openapi/openapi.php?serviceapi=" + encodeURIComponent(cfg.serviceapi || host)
                        + "&clientTitle=" + encodeURIComponent(brand)
                        + "&file=" + encodeURIComponent(file)
                        + "&v=" + Date.now();
            Redoc.init(specUrl, { hideDownloadButton: false, expandResponses: "200,201" }, document.getElementById("redoc-container"));
        })();
    </script>
</body>
</html>
EOF

    # Fill placeholders (quoted heredoc above prevents shell expansion; substitute now).
    sed -i \
        -e "s|__REDOC_VERSION__|$REDOC_VERSION|g" \
        -e "s|__ASSET_VERSION__|$ASSET_VERSION|g" \
        -e "s|__SERVICE_NAME__|$service_name|g" \
        -e "s|__SERVICE_FILE__|$spec_file|g" \
        "$out"
    echo "   🧭 Loader written: $output_name"
}

# output_name              spec_file          display_name
build_service "openapi.html"       "openapi.yaml"      "API"
build_service "flight.html"        "flight.yaml"       "Flight"
build_service "hotel.html"         "hotel.yaml"        "Hotel"
build_service "esim.html"          "esim.yaml"         "eSIM"
build_service "activity.html"      "activity.yaml"     "Activity"
build_service "visa.html"          "visa.yaml"         "Visa"
build_service "train.html"         "train.yaml"        "Train"
build_service "transfer.html"      "transfer.yaml"     "Transfer"
build_service "tour-package.html"  "tourpackage.yaml"  "TourPackage"

echo "✅ All documentation loaders generated in $REDOC_DIR"
echo ""
echo "🌐 View via a served domain, e.g. https://<domain>/doc/index.html"
echo "   (pages load specs dynamically from /openapi/openapi.php and brand per domain)"
