#!/usr/bin/env node
/**
 * project-inventory/index.ts — Entry point.
 */
import { Command } from 'commander';
import { writeText } from '../../../../lib/fs.js';
import { validateArgs } from './validate.js';
import { execute } from './execute.js';
import type { ProjectInventoryOutput, InventoryDomain } from './types.js';

const program = new Command();

program
  .name('project-inventory')
  .description('Deterministic scan of a SmartStack generated project')
  .requiredOption('--project-path <path>', 'Absolute path to the generated project root')
  .option('--output-file <path>', 'Optional path to dump the JSON report (stdout always populated)')
  .option('--domains <list>', 'Comma-separated domains (domain,data,api,frontend). Default = all.')
  .parse(process.argv);

const opts = program.opts();

const raw = {
  projectPath: opts.projectPath as string,
  outputFile: opts.outputFile as string | undefined,
  domains: typeof opts.domains === 'string'
    ? opts.domains.split(',').map((s: string) => s.trim()).filter(Boolean)
    : [],
};

const validation = validateArgs(raw);
if (!validation.valid || !validation.args) {
  const output: ProjectInventoryOutput = {
    success: false,
    command: 'project-inventory',
    data: { scannedAt: new Date().toISOString(), durationMs: 0, domainsRun: [] },
    report: null,
    errors: validation.errors,
    warnings: [],
    nextSteps: [],
  };
  console.log(JSON.stringify(output, null, 2));
  process.exit(1);
}

try {
  const { report, durationMs, domainsRun } = await execute(validation.args);
  const output: ProjectInventoryOutput = {
    success: true,
    command: 'project-inventory',
    data: {
      scannedAt: new Date().toISOString(),
      durationMs,
      domainsRun: domainsRun as InventoryDomain[],
    },
    report,
    errors: [],
    warnings: [],
    nextSteps: [],
  };
  const json = JSON.stringify(output, null, 2);
  if (validation.args.outputFile) {
    await writeText(validation.args.outputFile, json);
  }
  console.log(json);
  process.exit(0);
} catch (err) {
  const message = err instanceof Error ? err.message : String(err);
  const output: ProjectInventoryOutput = {
    success: false,
    command: 'project-inventory',
    data: { scannedAt: new Date().toISOString(), durationMs: 0, domainsRun: [] },
    report: null,
    errors: [`Unexpected error: ${message}`],
    warnings: [],
    nextSteps: [],
  };
  console.log(JSON.stringify(output, null, 2));
  process.exit(1);
}
