#!/usr/bin/env tsx

/**
 * Create a pull request for package release
 * Used by release-production.sh to create release PRs on GitHub
 */

import { createPullRequest } from "../utils/github-api";

interface CliArgs {
  sourceBranch: string;
  targetBranch: string;
  packageName: string;
  version: string;
  token: string;
}

function parseArgs(): CliArgs {
  const args = process.argv.slice(2);
  const parsed: Partial<CliArgs> = {};

  for (const arg of args) {
    if (arg.startsWith("--source-branch=")) {
      parsed.sourceBranch = arg.split("=")[1];
    } else if (arg.startsWith("--target-branch=")) {
      parsed.targetBranch = arg.split("=")[1];
    } else if (arg.startsWith("--package-name=")) {
      parsed.packageName = arg.split("=")[1];
    } else if (arg.startsWith("--version=")) {
      parsed.version = arg.split("=")[1];
    } else if (arg.startsWith("--token=")) {
      parsed.token = arg.split("=")[1];
    }
  }

  // Validate required arguments
  const required: (keyof CliArgs)[] = [
    "sourceBranch",
    "targetBranch",
    "packageName",
    "version",
    "token",
  ];
  for (const key of required) {
    if (!parsed[key]) {
      console.error(
        `Missing required argument: --${key.replace(/([A-Z])/g, "-$1").toLowerCase()}`,
      );
      process.exit(1);
    }
  }

  return parsed as CliArgs;
}

function buildDescription(
  packageName: string,
  version: string,
  releaseBranch: string,
): string {
  return `## Production Release

- **Package:** \`${packageName}\`
- **Version:** \`v${version}\`
- **Generated by:** Kumo CI Manual Release Pipeline

### Changes

- Version bump and changelog updates
- Published to npm registry

### Installation

\`\`\`bash
npm install ${packageName}@${version}
# or
pnpm add ${packageName}@${version}
\`\`\`

### Checklist

- [x] Package published successfully
- [x] Version bumped in package.json
- [x] Changelog updated
- [ ] Manual review completed

**Release branch:** \`${releaseBranch}\`

---
*Auto-generated by GitHub Actions*`;
}

async function main() {
  try {
    const args = parseArgs();

    console.log(
      `Creating pull request for ${args.packageName}@${args.version}...`,
    );

    const result = await createPullRequest(args.token, {
      sourceBranch: args.sourceBranch,
      targetBranch: args.targetBranch,
      title: `chore: release ${args.packageName}@${args.version}`,
      description: buildDescription(
        args.packageName,
        args.version,
        args.sourceBranch,
      ),
    });

    console.log(
      `Pull request created: ${result.html_url} (PR #${result.number})`,
    );
  } catch (error) {
    console.error("Failed to create pull request:", error);
    process.exit(1);
  }
}

main();
