#!/usr/bin/env node
/**
 * cli:merge — Merge a pull request with strategy
 * Responsabilité : Parse args → validate → execute → output JSON
 */
import { parseArgs } from 'node:util'
import { validate } from './validate.js'
import { execute } from './execute.js'
import type { MergeResult } 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:merge — Merge a pull request with strategy

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

Options:
  --spec   JSON spec with { squash?: boolean, merge?: boolean } (mutually exclusive)
  --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: MergeResult = {
      success: false,
      strategy: 'merge',
      target: '',
      branchDeleted: false,
      error: 'Invalid JSON in --spec',
    }
    output(result, values.json ?? false)
    process.exit(2)
  }
}

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

const validation = validate(spec)

if (!validation.valid) {
  const result: MergeResult = {
    success: false,
    strategy: 'merge',
    target: '',
    branchDeleted: false,
    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: MergeResult = {
      success: false,
      strategy: 'merge',
      target: '',
      branchDeleted: false,
      error: message,
    }
    output(result, values.json ?? false)
    process.exit(2)
  })

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

function output(data: MergeResult, json: boolean): void {
  if (json) {
    console.log(JSON.stringify(data, null, 2))
  } else {
    if (data.success) {
      console.log(`✓ PR #${data.prNumber} merged via ${data.strategy}`)
      console.log(`  Target: ${data.target}`)
      if (data.branchDeleted) {
        console.log(`  Source branch deleted`)
      }
    } else {
      console.error(`✗ Failed to merge PR: ${data.error}`)
    }
  }
}
