#!/usr/bin/env node
/**
 * cli:cleanup — Clean up merged worktrees and branches
 * Responsabilité : Parse args → validate → execute → output JSON
 */
import { parseArgs } from 'node:util'
import { validate } from './validate.js'
import { execute } from './execute.js'
import type { CleanupResult } from './types.js'

// ─── Parse des arguments ──────────────────────────────────────────────────────

const { values } = parseArgs({
  options: {
    spec: { type: 'string' },
    json: { type: 'boolean' },
    help: { type: 'boolean', short: 'h' },
  },
})

if (values.help) {
  console.log(`
cli:cleanup — Clean up merged worktrees and branches

Usage:
  npx ts-node cli/cleanup/index.ts --spec '<JSON>'

Options:
  --spec   JSON spec with { force?: boolean, dryRun?: boolean, staleDays?: number }
  --json   Output JSON only
  --help   Show this help
  `)
  process.exit(0)
}

// ─── Parse du JSON ────────────────────────────────────────────────────────────

let spec: unknown = {}

if (values.spec) {
  try {
    spec = JSON.parse(values.spec)
  } catch {
    const result: CleanupResult = {
      success: false,
      analyzed: 0,
      permanent: 0,
      active: 0,
      deleted: [],
      skipped: [],
      error: 'Invalid JSON in --spec',
    }
    output(result, values.json ?? false)
    process.exit(2)
  }
}

// ─── Validation ───────────────────────────────────────────────────────────────

const validation = validate(spec)

if (!validation.valid) {
  const result: CleanupResult = {
    success: false,
    analyzed: 0,
    permanent: 0,
    active: 0,
    deleted: [],
    skipped: [],
    error: validation.blockers.join('; '),
  }
  output(result, values.json ?? false)
  process.exit(2)
}

// ─── Exécution ────────────────────────────────────────────────────────────────

execute(validation.data as any, process.cwd())
  .then((result) => {
    output(result, values.json ?? false)
    const exitCode = result.success ? 0 : validation.blockers.length > 0 ? 2 : 1
    process.exit(exitCode)
  })
  .catch((err) => {
    const message = err instanceof Error ? err.message : String(err)
    const result: CleanupResult = {
      success: false,
      analyzed: 0,
      permanent: 0,
      active: 0,
      deleted: [],
      skipped: [],
      error: message,
    }
    output(result, values.json ?? false)
    process.exit(2)
  })

// ─── Helper ───────────────────────────────────────────────────────────────────

function output(data: CleanupResult, json: boolean): void {
  if (json) {
    console.log(JSON.stringify(data, null, 2))
  } else {
    if (data.success) {
      console.log(`✓ Cleanup complete`)
      console.log(`  Analyzed: ${data.analyzed}`)
      console.log(`  Permanent: ${data.permanent}`)
      console.log(`  Active: ${data.active}`)
      console.log(`  Deleted: ${data.deleted.length}`)
      if (data.deleted.length > 0) {
        for (const d of data.deleted) console.log(`    - ${d}`)
      }
      console.log(`  Skipped: ${data.skipped.length}`)
      if (data.skipped.length > 0) {
        for (const s of data.skipped) console.log(`    - ${s}`)
      }
    } else {
      console.error(`✗ Cleanup failed: ${data.error}`)
    }
  }
}
