/**
 * Pull Request Creation Command
 * Creates a PR with AI-generated description
 */

import { exec } from 'child_process'
import { promisify } from 'util'
import { readFileSync } from 'fs'

const execAsync = promisify(exec)

export interface PRCreateOptions {
  title?: string
  base?: string
  draft?: boolean
  reviewers?: string[]
}

export async function handle(args: PRCreateOptions, context: any): Promise<string> {
  const { title, base = 'main', draft = false, reviewers } = args

  try {
    // Get current branch
    const { stdout: branchOutput } = await execAsync('git rev-parse --abbrev-ref HEAD')
    const branch = branchOutput.trim()

    // Get default title from branch name if not provided
    const prTitle = title || branchToTitle(branch)

    // Get commits for description
    const { stdout: commits } = await execAsync(`git log ${base}..HEAD --oneline`)

    // Generate description
    const description = `## Changes\n\n${commits}\n\n## Summary\n\nAutomated PR created from branch ${branch}`

    // Create PR using gh CLI
    const draftFlag = draft ? '--draft' : ''
    const reviewersFlag = reviewers ? `--reviewer ${reviewers.join(',')}` : ''

    const { stdout } = await execAsync(
      `gh pr create --base ${base} --title "${prTitle}" --body "${description}" ${draftFlag} ${reviewersFlag}`
    )

    return `✓ Pull request created:\n${stdout}`
  } catch (error: any) {
    throw new Error(`PR creation failed: ${error.message}`)
  }
}

function branchToTitle(branch: string): string {
  return branch
    .replace(/^(feat|fix|docs|style|refactor|test|chore)\//i, '')
    .replace(/-/g, ' ')
    .replace(/_/g, ' ')
    .split(' ')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ')
}

export default { handle }
