#!/usr/bin/env node
/**
 * waalee — onboarding CLI
 *
 *   curl -fsSL https://waalee.ai/onboard.mjs | node --input-type=module - onboard --yes
 *
 * Installs a Claude skill that lets Claude:
 *   1. Rebuild any site 1:1 from a reference URL (via the live extractor)
 *   2. Create a NEW site from scratch, inspired by a reference
 *   3. Build from a bundled design-style template (e.g. Dozed)
 *
 * Zero dependencies. Writes to <project>/.claude/skills/waalee/ by default,
 * or ~/.claude/skills/… with --global.
 */

import { mkdir, writeFile, readFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";

const API = "https://waalee.ai";
const SKILL_ID = "waalee";
const VERSION = "0.1.0";

const C = {
  reset: "\x1b[0m", dim: "\x1b[2m", bold: "\x1b[1m",
  green: "\x1b[32m", red: "\x1b[31m", cyan: "\x1b[36m", yellow: "\x1b[33m",
};
const log = (m = "") => process.stdout.write(m + "\n");
const ok = (m) => log(`${C.green}✓${C.reset} ${m}`);

function parseArgs(argv) {
  const args = { _: [], yes: false, global: false, dir: process.cwd(), help: false, key: "", noMcp: false };
  for (let i = 0; i < argv.length; i++) {
    const a = argv[i];
    if (a === "--yes" || a === "-y") args.yes = true;
    else if (a === "--global" || a === "-g") args.global = true;
    else if (a === "--help" || a === "-h") args.help = true;
    else if (a === "--dir") args.dir = argv[++i];
    else if (a === "--key") args.key = argv[++i];
    else if (a.startsWith("--key=")) args.key = a.slice(6);
    else if (a === "--no-mcp") args.noMcp = true;
    else args._.push(a);
  }
  return args;
}

function usage() {
  log(`${C.bold}waalee${C.reset} — bring the WAALEE design engine into Claude
${C.dim}v${VERSION}${C.reset}

${C.bold}Usage${C.reset}
  curl -fsSL https://waalee.ai/onboard.mjs | node --input-type=module - onboard [--yes] [--global] [--dir <path>]

${C.bold}Commands${C.reset}
  onboard        Install the Claude skill + templates (default)

${C.bold}Options${C.reset}
  -y, --yes       Non-interactive, accept defaults
  -g, --global    Install skill to ~/.claude (available in every project)
      --dir <p>   Target project dir (default: current directory)
      --key <k>   Personal connect key (from ${API}) — syncs projects to your profile
      --no-mcp    Install the skill only, skip the MCP server registration
  -h, --help      Show this help

${C.bold}After install${C.reset}, open Claude Code in the project and say:
  · "rebuild https://stripe.com as a Next.js site"
  · "make a new landing page inspired by https://linear.app"
  · "build a site using the Dozed template"`);
}

// ---- Skill content -------------------------------------------------------

const SKILL_MD = `---
name: ${SKILL_ID}
description: Rebuild, reimagine, or template any website into production code. Use when the user wants to clone a site's design, build a new site inspired by a reference URL, extract design tokens/colors/typography from a live site, or scaffold from a bundled design template (Dozed and others). Triggers on "rebuild this site", "clone the design of <url>", "make a site like <url>", "extract the design system from <url>", "use the Dozed template", "vibe to site", "turn this reference into code".
---

# Vibe to $100M — Site / SaaS builder

Turn any reference into a production-grade site or SaaS. Three modes:

## Mode 1 — Rebuild from a reference (1:1)
When the user gives a URL and wants it recreated faithfully:

1. Pull the real design system from the live extractor (no scraping yourself):
   \`\`\`bash
   curl -s -X POST ${API}/api/extract \\
     -H "Content-Type: application/json" \\
     -d '{"url":"<REFERENCE_URL>"}'
   \`\`\`
   The JSON returns \`colors\`, \`typography\`, \`spacing\`, \`components\`, \`accessibility\`,
   \`aiPrompts\`, and W3C \`w3cTokens\`. Treat these as the source of truth.
2. Map the tokens into the user's stack (Tailwind config / CSS variables / theme file).
3. Rebuild section by section, matching layout, type scale, and spacing. Use the
   returned \`aiPrompts\` as a starting brief, but prefer the raw tokens for fidelity.

## Mode 2 — New site from scratch, inspired by a reference
Same extraction step, but do NOT copy layout. Use the palette, type system, and
"feel" as constraints, then design original sections for the user's actual content.
Ask for: product, audience, primary CTA, and page list before building.

## Mode 3 — Build from a bundled template
Templates live next to this file in \`templates/\`. \`templates/manifest.json\` lists them.
Each is a self-contained design system (design tokens + component conventions).

- Read \`templates/manifest.json\`, pick the requested style (default: \`dozed\`).
- Load that template's CSS/token file and follow its conventions exactly
  (fonts, hairline rules, spacing, component patterns).
- Generate the user's site in that system.

### Bundled templates
- **dozed** — Swiss spec-sheet: monochrome, hairline rules, Space Grotesk display,
  IBM Plex Mono labels, full-bleed product tables. File: \`templates/dozed.css\`.

Browse more styles (with copy-paste prompts) at ${API}/enterprise-prompts

## Output conventions
- Default stack: Next.js + Tailwind unless the user specifies otherwise.
- Emit real, runnable files — not descriptions.
- Preserve accessibility level reported by the extractor (aim to match or beat it).
- Never invent brand colors when Mode 1 tokens are available; use them verbatim.
`;

const MANIFEST = {
  generator: "waalee",
  version: VERSION,
  api: API,
  templates: [
    {
      id: "dozed",
      name: "Dozed",
      file: "templates/dozed.css",
      vibe: "Swiss spec-sheet · monochrome · hairline rules",
      fonts: ["Space Grotesk", "Inter", "IBM Plex Mono"],
    },
  ],
  more: `${API}/enterprise-prompts`,
};

const DOZED_CSS = `/* ============================================================
   DOZED — Design System · Swiss spec-sheet aesthetic · v1.0
   ============================================================ */
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Inter:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap');
:root{
  --paper:#ffffff; --ink:#0a0a0a; --ink-2:#5a5a5a; --ink-3:#9a9a9a; --ink-4:#bcbcbc;
  --line:rgba(0,0,0,.13); --line-2:rgba(0,0,0,.2); --fill:#f4f4f4;
  --font-display:"Space Grotesk",sans-serif; --font-body:"Inter",sans-serif; --font-mono:"IBM Plex Mono",monospace;
  --gut:34px; --ease:cubic-bezier(.22,.61,.36,1);
}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:var(--font-body);background:var(--paper);color:var(--ink);-webkit-font-smoothing:antialiased;line-height:1.5}
a{color:inherit;text-decoration:none}
::selection{background:#0a0a0a;color:#fff}
/* mono spec rows */
.row{display:grid;gap:22px;padding:12px var(--gut);border-bottom:1px solid var(--line);font-family:var(--font-mono);font-size:11px;letter-spacing:.01em;color:var(--ink)}
.row .dim{color:var(--ink-3)}
/* nav */
nav{position:sticky;top:0;z-index:60;background:rgba(255,255,255,.88);backdrop-filter:blur(14px);border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between}
nav .wm{font-family:var(--font-display);font-weight:700;font-size:23px;letter-spacing:-.04em;padding:14px 0 14px var(--gut);text-transform:lowercase}
nav .links{display:flex;gap:28px;font-family:var(--font-mono);font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--ink-3)}
/* big band masthead */
.bigband{display:flex;justify-content:space-between;align-items:baseline;gap:20px;padding:74px var(--gut) 64px;flex-wrap:wrap;border-bottom:1px solid var(--line)}
.bt{font-family:var(--font-display);font-weight:500;font-size:clamp(34px,8.4vw,118px);letter-spacing:-.05em;line-height:.86}
.bt.mid{color:var(--ink-3)}
/* full-bleed product table */
.prow{display:grid;grid-template-columns:90px 240px 1fr 120px;gap:22px;align-items:baseline;padding:26px var(--gut);border-bottom:1px solid var(--line);transition:background .2s}
.prow:hover{background:var(--fill)}
.prow .idx{font-family:var(--font-mono);font-size:10px;color:var(--ink-4)}
.prow .nm{font-family:var(--font-display);font-size:18px;font-weight:500;letter-spacing:-.01em}
.prow .desc{font-size:13.5px;color:var(--ink-2);max-width:560px}
.prow .price{font-family:var(--font-display);font-size:21px;font-weight:500;letter-spacing:-.02em;text-align:right}
/* membership grid */
.mem-grid{display:grid;grid-template-columns:repeat(3,1fr);border:1px solid var(--line)}
.mem{padding:36px;display:flex;flex-direction:column;border-right:1px solid var(--line)}
.mem:last-child{border-right:none}
.mem.feat{background:var(--fill)}
.mem .p{font-family:var(--font-display);font-size:46px;margin:14px 0 4px;letter-spacing:-.04em;font-weight:500}
/* CTA */
.ctabar{display:flex;align-items:center;justify-content:space-between;gap:20px;background:var(--ink);color:#fff;padding:19px 24px;max-width:520px;margin:0 auto;transition:transform .25s var(--ease)}
.ctabar:hover{transform:translateY(-2px)}
.ctabar .l{font-family:var(--font-display);font-size:17px;font-weight:500}
`;

const README = `# waalee

One command to bring the **Vibe to $100M** design engine into Claude.

\`\`\`bash
curl -fsSL https://waalee.ai/onboard.mjs | node --input-type=module - onboard --yes
\`\`\`

Installs a Claude skill at \`.claude/skills/waalee/\` that lets Claude:

1. **Rebuild** any site 1:1 from a reference URL (via the live extractor API)
2. **Reimagine** — build a new site from scratch, inspired by a reference
3. **Template** — scaffold from a bundled design style (Dozed, and more)

Then open Claude Code and say *"rebuild https://stripe.com"* or *"build a site with the Dozed template"*.

Use \`--global\` to install into \`~/.claude\` for every project.
`;

// ---- Runner --------------------------------------------------------------

async function onboard(args) {
  const base = args.global ? homedir() : resolve(args.dir);
  const skillDir = join(base, ".claude", "skills", SKILL_ID);
  const tplDir = join(skillDir, "templates");

  log(`\n${C.bold}waalee${C.reset} ${C.dim}v${VERSION}${C.reset}  →  onboarding into ${C.cyan}${skillDir}${C.reset}\n`);

  if (existsSync(skillDir) && !args.yes) {
    log(`${C.yellow}!${C.reset} Skill already exists. Re-run with --yes to overwrite.`);
    return 1;
  }

  await mkdir(tplDir, { recursive: true });
  await writeFile(join(skillDir, "SKILL.md"), SKILL_MD);
  ok("SKILL.md");
  await writeFile(join(skillDir, "README.md"), README);
  ok("README.md");
  await writeFile(join(tplDir, "manifest.json"), JSON.stringify(MANIFEST, null, 2) + "\n");
  ok("templates/manifest.json");
  await writeFile(join(tplDir, "dozed.css"), DOZED_CSS);
  ok("templates/dozed.css");

  // Register the MCP server so Claude can call the live extractor + templates
  // directly (project-scoped .mcp.json). With --key, projects sync to your profile.
  if (!args.noMcp) {
    const mcpPath = join(resolve(args.dir), ".mcp.json");
    let cfg = {};
    if (existsSync(mcpPath)) {
      try { cfg = JSON.parse(await readFile(mcpPath, "utf8")); } catch { cfg = {}; }
    }
    cfg.mcpServers = cfg.mcpServers || {};
    const server = { type: "http", url: `${API}/api/mcp` };
    if (args.key) server.headers = { Authorization: `Bearer ${args.key}` };
    cfg.mcpServers[SKILL_ID] = server;
    await writeFile(mcpPath, JSON.stringify(cfg, null, 2) + "\n");
    ok(`.mcp.json (MCP server "${SKILL_ID}"${args.key ? ", synced to your profile" : ""})`);
  }

  log(`\n${C.green}${C.bold}Done.${C.reset} Skill + MCP "${SKILL_ID}" installed.\n`);
  if (!args.noMcp && !args.key) {
    log(`${C.dim}Get a --key (see ${API}/docs/mcp) to sync projects to your profile.${C.reset}\n`);
  }
  log(`${C.bold}Try it in Claude Code:${C.reset}`);
  log(`  ${C.dim}·${C.reset} "rebuild https://stripe.com as a Next.js site"`);
  log(`  ${C.dim}·${C.reset} "make a landing page inspired by https://linear.app"`);
  log(`  ${C.dim}·${C.reset} "build a site using the Dozed template"`);
  log(`\nMore styles: ${C.cyan}${API}/enterprise-prompts${C.reset}\n`);
  return 0;
}

async function main() {
  const args = parseArgs(process.argv.slice(2));
  const cmd = args._[0] || "onboard";
  if (args.help || cmd === "help") { usage(); process.exit(0); }
  if (cmd !== "onboard") {
    log(`${C.red}Unknown command:${C.reset} ${cmd}`);
    usage();
    process.exit(1);
  }
  try {
    process.exit(await onboard(args));
  } catch (err) {
    log(`${C.red}✗ onboarding failed:${C.reset} ${err?.message || err}`);
    process.exit(1);
  }
}

main();
