#!/usr/bin/env node
// Create demo pages from Nordic Fresh Foods agent output for Starlight
import { readFileSync, writeFileSync, existsSync } from "fs";

const SRC = "agent-output/nordic-fresh-foods";
const DEST = "site/src/content/docs/demo";

const PAGES = [
  {
    src: null,
    dest: "index.md",
    title: "Demo: Nordic Fresh Foods",
    description:
      "Complete end-to-end walkthrough of the APEX pipeline using the Nordic Fresh Foods scenario",
    custom: true,
  },
  {
    src: "01-requirements.md",
    dest: "01-requirements.md",
    title: "Step 1 — Requirements",
    description:
      "Business and technical requirements captured by the Requirements agent",
  },
  {
    src: "02-architecture-assessment.md",
    dest: "02-architecture.md",
    title: "Step 2 — Architecture",
    description:
      "Well-Architected Framework assessment and SKU recommendations",
  },
  {
    src: null,
    dest: "03-design.md",
    title: "Step 3 — Design",
    description:
      "Architecture Decision Records, cost estimates, and design diagrams",
    custom: true,
  },
  {
    src: "04-governance-constraints.md",
    dest: "04-governance.md",
    title: "Step 3.5 — Governance",
    description:
      "Azure Policy constraints discovered from the target subscription",
  },
  {
    src: "04-implementation-plan.md",
    dest: "05-plan.md",
    title: "Step 4 — Implementation Plan",
    description:
      "Module-by-module implementation plan with dependency ordering",
  },
  {
    src: "05-implementation-reference.md",
    dest: "06-code.md",
    title: "Step 5 — Code",
    description: "Bicep code generation results and implementation reference",
  },
  {
    src: "06-deployment-summary.md",
    dest: "07-deploy.md",
    title: "Step 6 — Deployment",
    description: "Deployment execution results and deployed resource inventory",
  },
  {
    src: null,
    dest: "08-as-built.md",
    title: "Step 7 — As-Built Documentation",
    description: "Complete post-deployment documentation suite",
    custom: true,
  },
  {
    src: null,
    dest: "09-reviews.md",
    title: "Adversarial Reviews",
    description: "Challenger agent findings across all workflow steps",
    custom: true,
  },
];

function cleanContent(content) {
  // Strip MkDocs badge images
  content = content.replace(
    /^!\[.*?\]\(https:\/\/img\.shields\.io\/.*?\)\s*\n?/gm,
    "",
  );
  // Strip <details open> / </details> / <summary> wrappers
  content = content.replace(/<details[^>]*>\s*\n?/g, "");
  content = content.replace(/<\/details>\s*\n?/g, "");
  content = content.replace(/<summary>.*?<\/summary>\s*\n?/g, "");
  // Strip first H1 (Starlight generates from frontmatter)
  content = content.replace(/^#\s+.+\n\n?/, "");
  // Strip leading empty lines
  content = content.replace(/^\n+/, "");
  return content;
}

function buildFrontmatter(page, order) {
  return `---\ntitle: "${page.title}"\ndescription: "${page.description}"\nsidebar:\n  order: ${order}\n---\n\n`;
}

// Build index page
function buildIndexPage() {
  return `---
title: "Demo: Nordic Fresh Foods"
description: "Complete end-to-end walkthrough of the APEX pipeline"
sidebar:
  order: 0
---

:::tip[Live Agent Output]
Every page in this demo section contains **actual output** from the APEX pipeline — generated by AI agents, reviewed by the Challenger agent, and validated by automated checks. Nothing was manually written.
:::

## Project Overview

**Nordic Fresh Foods** is a Stockholm-based farm-to-table delivery company preparing for peak season. They need secure, scalable Azure infrastructure supporting online ordering, operations reporting, and future growth.

This demo walks through the complete multi-step workflow output — from requirements capture to as-built documentation — showing exactly what the agents produce.

## Architecture

![Nordic Fresh Foods Architecture](/azure-agentic-infraops/demo/03-des-diagram.png)

## Workflow Steps

| Step | Agent | Output |
|------|-------|--------|
| **1. Requirements** | Requirements Agent | [Business & technical requirements](01-requirements/) |
| **2. Architecture** | Architect Agent | [WAF assessment + cost estimate](02-architecture/) |
| **3. Design** | Design Agent | [ADRs + diagrams + cost charts](03-design/) |
| **3.5 Governance** | Governance Agent | [Azure Policy constraints](04-governance/) |
| **4. Plan** | IaC Planner | [Implementation plan + dependency diagram](05-plan/) |
| **5. Code** | CodeGen Agent | [Bicep templates (AVM-first)](06-code/) |
| **6. Deploy** | Deploy Agent | [Deployment results](07-deploy/) |
| **7. As-Built** | As-Built Agent | [Complete documentation suite](08-as-built/) |
| **Reviews** | Challenger Agent | [Adversarial findings](09-reviews/) |

## Key Stats

| Metric | Value |
|--------|-------|
| **Workflow steps** | 7 (+ governance discovery) |
| **Adversarial reviews** | 12 challenge passes |
| **IaC track** | Bicep (AVM-first) |
| **Region** | Sweden Central |
| **Diagrams generated** | 11 PNG artifacts |

[**Start the walkthrough →**](01-requirements/)
`;
}

// Build design page (combines multiple artifacts)
function buildDesignPage() {
  const parts = [];
  parts.push(`---
title: "Step 3 — Design"
description: "Architecture Decision Records, cost estimates, and design diagrams"
sidebar:
  order: 3
---

## Architecture Diagram

![Architecture Diagram](/azure-agentic-infraops/demo/03-des-diagram.png)

## Cost Distribution

![Cost Distribution](/azure-agentic-infraops/demo/03-des-cost-distribution.png)

## Cost Projection

![Cost Projection](/azure-agentic-infraops/demo/03-des-cost-projection.png)

## Architecture Decision Record
`);

  const adrFile = `${SRC}/03-des-adr-0001-cost-optimized-n-tier-azure-architecture.md`;
  if (existsSync(adrFile)) {
    let adr = readFileSync(adrFile, "utf-8");
    adr = cleanContent(adr);
    parts.push(adr);
  }

  parts.push(`\n## Cost Estimate\n`);
  const costFile = `${SRC}/03-des-cost-estimate.md`;
  if (existsSync(costFile)) {
    let cost = readFileSync(costFile, "utf-8");
    cost = cleanContent(cost);
    parts.push(cost);
  }

  return parts.join("\n");
}

// Build as-built page (combines 7 docs)
function buildAsBuiltPage() {
  const docs = [
    { file: "07-design-document.md", heading: "Design Document" },
    { file: "07-operations-runbook.md", heading: "Operations Runbook" },
    { file: "07-backup-dr-plan.md", heading: "Backup & DR Plan" },
    { file: "07-compliance-matrix.md", heading: "Compliance Matrix" },
    { file: "07-resource-inventory.md", heading: "Resource Inventory" },
    { file: "07-ab-cost-estimate.md", heading: "Cost Estimate" },
  ];

  let content = `---
title: "Step 7 — As-Built Documentation"
description: "Complete post-deployment documentation suite"
sidebar:
  order: 8
---

:::note[Documentation Suite]
The As-Built agent generates a complete documentation package after successful deployment. Each section below is a separate artifact produced by the agent.
:::

## Architecture (As-Built)

![As-Built Architecture](/azure-agentic-infraops/demo/07-ab-diagram.png)

## Cost Distribution (Actual)

![Cost Distribution](/azure-agentic-infraops/demo/07-ab-cost-distribution.png)

## Cost Comparison (Estimated vs Actual)

![Cost Comparison](/azure-agentic-infraops/demo/07-ab-cost-comparison.png)

## Compliance Gaps

![Compliance Gaps](/azure-agentic-infraops/demo/07-ab-compliance-gaps.png)

`;

  for (const doc of docs) {
    const path = `${SRC}/${doc.file}`;
    if (existsSync(path)) {
      let body = readFileSync(path, "utf-8");
      body = cleanContent(body);
      // Downgrade H2 to H3 to fit under our H2 sections
      body = body.replace(/^## /gm, "### ");
      content += `\n---\n\n## ${doc.heading}\n\n${body}\n`;
    }
  }

  return content;
}

// Build reviews page
function buildReviewsPage() {
  const files = [
    "challenge-findings-requirements.json",
    "challenge-findings-architecture-pass1.json",
    "challenge-findings-architecture-pass2.json",
    "challenge-findings-architecture-pass3.json",
    "challenge-findings-cost-estimate.json",
    "challenge-findings-governance-constraints-pass1.json",
    "challenge-findings-governance-revalidation.json",
    "challenge-findings-plan-pass1.json",
    "challenge-findings-plan-pass2.json",
    "challenge-findings-plan-pass3.json",
    "challenge-findings-plan-revalidation.json",
    "challenge-findings-deployment.json",
  ];

  let content = `---
title: "Adversarial Reviews"
description: "Challenger agent findings across all workflow steps"
sidebar:
  order: 9
---

:::caution[Adversarial Review]
The Challenger agent runs rotating-lens reviews at each workflow step — checking for security gaps, governance violations, WAF blind spots, and cost issues. Findings below are actual agent output.
:::

## Review Summary

| Review | Lens | Findings |
|--------|------|----------|
`;

  for (const file of files) {
    const path = `${SRC}/${file}`;
    if (!existsSync(path)) continue;
    try {
      const data = JSON.parse(readFileSync(path, "utf-8"));
      const name = file
        .replace("challenge-findings-", "")
        .replace(".json", "")
        .replace(/-/g, " ");
      const lens = data.lens || data.review_lens || "comprehensive";
      const count = data.findings?.length || data.must_fix?.length || 0;
      const should = data.should_fix?.length || 0;
      content += `| ${name} | ${lens} | ${count} must-fix, ${should} should-fix |\n`;
    } catch {
      // skip malformed
    }
  }

  content += `\n## Detailed Findings\n\n`;

  for (const file of files) {
    const path = `${SRC}/${file}`;
    if (!existsSync(path)) continue;
    try {
      const data = JSON.parse(readFileSync(path, "utf-8"));
      const name = file
        .replace("challenge-findings-", "")
        .replace(".json", "")
        .replace(/-/g, " ");
      content += `\n### ${name}\n\n`;

      const allFindings = [
        ...(data.must_fix || []).map((f) => ({ ...f, severity: "must-fix" })),
        ...(data.should_fix || []).map((f) => ({
          ...f,
          severity: "should-fix",
        })),
        ...(data.findings || []).map((f) => ({
          ...f,
          severity: f.severity || "info",
        })),
      ];

      if (allFindings.length === 0) {
        content += `No findings.\n`;
        continue;
      }

      for (const f of allFindings.slice(0, 5)) {
        const title = f.title || f.finding || f.description || "Finding";
        const sev = f.severity || "info";
        content += `- **[${sev}]** ${title}\n`;
      }
      if (allFindings.length > 5) {
        content += `- *...and ${allFindings.length - 5} more findings*\n`;
      }
    } catch {
      // skip
    }
  }

  return content;
}

// Process all pages
let order = 0;
for (const page of PAGES) {
  let content;

  if (page.custom) {
    if (page.dest === "index.md") content = buildIndexPage();
    else if (page.dest === "03-design.md") content = buildDesignPage();
    else if (page.dest === "08-as-built.md") content = buildAsBuiltPage();
    else if (page.dest === "09-reviews.md") content = buildReviewsPage();
  } else {
    const srcPath = `${SRC}/${page.src}`;
    if (!existsSync(srcPath)) {
      console.warn(`⚠️  Missing: ${srcPath}`);
      order++;
      continue;
    }
    let body = readFileSync(srcPath, "utf-8");
    body = cleanContent(body);
    content = buildFrontmatter(page, order) + body;
  }

  writeFileSync(`${DEST}/${page.dest}`, content);
  console.log(`✅ ${page.dest}`);
  order++;
}

console.log(`\n✅ Done: ${PAGES.length} demo pages created`);
