#!/usr/bin/env node
/**
 * cli:scaffold-layout — Scaffold app-level layout shell.
 *
 * Idempotent: skips writes if existing file content matches; honors
 * `/* @customised *\/` (or `// @customised`) marker at the top of the file.
 */
import { parseArgs } from 'node:util';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { validate } from './validate.js';
import { generate } from './generate.js';
import { generateEnvelope, failGenerate, printEnvelope } from '../../../../../lib/output.js';

const COMMAND = 'scaffold-layout';

function isCustomised(source: string): boolean {
  const head = source.trimStart().slice(0, 100);
  return head.startsWith('/* @customised') || head.startsWith('// @customised');
}

function main(): void {
  const { values } = parseArgs({
    options: {
      spec: { type: 'string' },
      dry_run: { type: 'boolean', default: false },
    },
    strict: true,
  });

  if (!values.spec) {
    printEnvelope(failGenerate(COMMAND, ['--spec is required']));
    process.exit(1);
  }

  let raw: unknown;
  try {
    raw = JSON.parse(values.spec);
  } catch {
    printEnvelope(failGenerate(COMMAND, ['Invalid JSON in --spec']));
    process.exit(1);
  }

  const validation = validate(raw);
  if (!validation.valid || !validation.spec) {
    printEnvelope(failGenerate(COMMAND, validation.errors));
    process.exit(1);
  }

  const spec = validation.spec;
  const files = generate(spec);

  if (values.dry_run) {
    printEnvelope(generateEnvelope(COMMAND, {
      data: { dryRun: true, files: files.map((f) => f.path) },
      warnings: validation.warnings,
    }));
    process.exit(0);
  }

  const filesCreated: string[] = [];
  const filesModified: string[] = [];
  const skipped: string[] = [];

  for (const file of files) {
    const abs = resolve(join(spec.projectPath, file.path));
    if (existsSync(abs)) {
      const existing = readFileSync(abs, 'utf-8');
      if (isCustomised(existing)) {
        skipped.push(file.path);
        continue;
      }
      if (!spec.force && existing === file.content) continue;
      mkdirSync(dirname(abs), { recursive: true });
      writeFileSync(abs, file.content, 'utf-8');
      filesModified.push(abs);
    } else {
      mkdirSync(dirname(abs), { recursive: true });
      writeFileSync(abs, file.content, 'utf-8');
      filesCreated.push(abs);
    }
  }

  const nextSteps: string[] = [];
  if (skipped.length > 0) {
    nextSteps.push(`Skipped ${skipped.length} customised file(s): ${skipped.join(', ')}. Remove the @customised marker to allow overwrites.`);
  }
  if (filesCreated.length === 0 && filesModified.length === 0 && skipped.length === 0) {
    nextSteps.push('Layout already up-to-date — no changes needed.');
  }
  if (filesCreated.length > 0) {
    nextSteps.push('Wrap your routes in <AppShell> at src/main.tsx (or App.tsx) to mount the new shell.');
  }

  printEnvelope(generateEnvelope(COMMAND, {
    data: { fileCount: filesCreated.length + filesModified.length, skipped: skipped.length },
    filesCreated,
    filesModified,
    warnings: validation.warnings,
    nextSteps,
  }));
}

main();
