#!/usr/bin/env node
/**
 * cli:pr — Create a pull request for current branch
 * Responsabilité : Parse args → validate → execute → output JSON
 */
import { parseArgs } from 'node:util'
import { validate } from './validate.js'
import { execute } from './execute.js'
import type { PrResult } from './types.js'

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

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

if (values.help) {
  console.log(`
cli:pr — Create a pull request for current branch

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

Options:
  --spec   JSON spec with { draft?: boolean } (default: {})
  --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: PrResult = {
      success: false,
      provider: 'unknown',
      title: '',
      source: '',
      target: '',
      draft: false,
      error: 'Invalid JSON in --spec',
    }
    output(result, values.json ?? false)
    process.exit(2)
  }
}

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

const validation = validate(spec)

if (!validation.valid) {
  const result: PrResult = {
    success: false,
    provider: 'unknown',
    title: '',
    source: '',
    target: '',
    draft: 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: PrResult = {
      success: false,
      provider: 'unknown',
      title: '',
      source: '',
      target: '',
      draft: false,
      error: message,
    }
    output(result, values.json ?? false)
    process.exit(2)
  })

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

function output(data: PrResult, json: boolean): void {
  if (json) {
    console.log(JSON.stringify(data, null, 2))
  } else {
    if (data.success) {
      console.log(`✓ PR created: ${data.prUrl}`)
      console.log(`  Title: ${data.title}`)
      console.log(`  ${data.source} → ${data.target}`)
      console.log(`  Provider: ${data.provider}`)
    } else {
      console.error(`✗ Failed to create PR: ${data.error}`)
    }
  }
}
