#!/usr/bin/env node
const { program } = require('commander');

const {
  mpUploadAndReportByOptions,
  writeEnvAndPrivateKeyByOptions,
  cleanChangelogScript,
} = require('../lib');
const { version } = require('../package.json');

const { deployGithubPage } = require('./deploy-github-page');
const { deployPagesCommand } = require('./deploy-pages');
const { mergeBranchesCommand } = require('./merge-branches');
const { publish } = require('./publish');

program
  .name('t-comm')
  .description('CLI for t-comm')
  .version(version);


program.command('publish')
  .description('Publish to server with bash script')
  // .argument('<string>', 'string to split')
  // .option('--first', 'display just the first substring')
  .option('-s, --source <string>', 'source dir or file')
  .option('-t, --target <string>', 'target dir')
  .option('-n, --name <ip>', 'server host name')
  .option('-p, --password <string>', 'server host password')
  .option('-o, --port <number>', 'server port', 36000)
  .action(publish);


program.command('mp-env')
  .description('Write Env and Private Key to File')
  // base
  .option('-b, --branch <string>', 'git branch')
  .option('-e --env <string>', 'publish env', 'test')
  .option('-r --root <string>', 'target file path', process.cwd())
  // rainbow
  .option('-k, --configKey <string>', 'rainbow config key')
  .option('-a, --appid <string>', 'rainbow app id')
  .option('--envName <string>', 'rainbow env name', 'Default')
  .option('-g, --groupName <string>', 'rainbow group name')
  .action(writeEnvAndPrivateKeyByOptions);


program.command('mp-upload')
  .description('Upload MiniProgram Bundle and Report')
  // base
  .option('-b, --branch <string>', 'git branch')
  .option('-e --env <string>', 'publish env', 'test')
  .option('-r --root <string>', 'target file path', process.cwd())
  // rainbow
  .option('-k, --configKey <string>', 'rainbow config key')
  .option('-a, --appid <string>', 'rainbow app id')
  .option('--envName <string>', 'rainbow env name', 'Default')
  .option('-g, --groupName <string>', 'rainbow group name')
  // rd
  .option('--rdHost <string>', 'host of R&D platform')
  // bk
  .option('--bkStartType <string>', 'start type in bk ci')
  .option('--bkBuildUrl <string>', 'build url in bk ci')
  .option('--bkStartUserName <string>', 'start user name in bk ci')
  .option('--bkPipelineId <string>', 'pipeline id in bk ci')
  // commit
  .option('--commitAuthor <string>', 'author of last commit')
  .option('--commitMessage <string>', 'message of last commit')
  .option('--commitHash <string>', 'hash of last commit')
  // version
  .option('--mpVersion <string>', 'miniProgram bundle version')
  .action(mpUploadAndReportByOptions);


program
  .command('deploy:github')
  .description('Deploy Github Page')
  .option('--repo <repo>', 'Repository Name')
  .option('--user <user>', 'User Name')
  .option('--email <email>', 'Login Email')
  .option('--dir <dir>', 'Target Directory')
  .option('--token <token>', 'Github Token')
  .option('--branch <branch>', 'Repository Branch')
  .option('--message <message>', 'Commit Message')
  .option('--increment <increment>', 'Is Increment')
  .option('--playgroundDir <playgroundDir>', 'Playground Dir')
  .option('--targetDirName <targetDirName>', 'Target Dir Name')
  .action(deployGithubPage);


program
  .command('clean:changelog')
  .description('Clean changelog files by removing alpha/beta versions')
  .argument('<patterns...>', 'CHANGELOG.md file paths or glob patterns')
  .option('-d, --dry-run', 'Preview mode, do not actually modify files')
  .action(async (patterns, options) => {
    try {
      const args = [...patterns];
      if (options.dryRun) {
        args.push('--dry-run');
      }
      await cleanChangelogScript(args);
    } catch (error) {
      console.error('❌ Error cleaning changelog:', error.message);
      process.exit(1);
    }
  });


program
  .command('deploy:pages')
  .description('Deploy directory to OA Pages (pages.woa.com)')
  .argument('<cname>', 'Domain name, e.g. t-comm.pages.woa.com or t-comm')
  .argument('<directory>', 'Local directory to deploy')
  .option('-k, --api-key <key>', 'OA Pages API Key (defaults to OA_PAGES_API_KEY env)')
  .option('-v, --visibility <type>', 'Access permission: public | tof | whitelist')
  .option('-d, --description <text>', 'Site description (max 100 chars)')
  .option('--dry-run', 'Preview mode, do not actually upload')
  .action(deployPagesCommand);


program
  .command('merge-branches')
  .description('Merge a source branch (or MR) into the target branch via TGit API')
  .argument('[mrUrl]', 'TGit MR URL, e.g. https://git.woa.com/group/project/-/merge_requests/123 (auto resolve project & branches)')
  .option('--mr <url>', 'TGit MR URL (alternative to positional argument)')
  .option('--id <id>', 'Project ID or full path (required when MR URL not provided)')
  .option('-s, --source <branch>', 'Source branch name or commit SHA')
  .option('-t, --target <branch>', 'Target branch name')
  .option('--source-project-id <id>', 'Source project ID for cross-project MR')
  .option('--merge-type <type>', 'merge | rebase | squash', 'merge')
  .option('--commit-message <message>', 'Commit message (required for rebase)')
  .option('--private-token <token>', 'TGit private token (defaults to GIT_WOA_PRIVATE_TOKEN env)')
  .option('--base-url <url>', 'TGit API base URL (defaults to GIT_WOA_BASE_URL env)')
  .action((mrUrl, options) => mergeBranchesCommand({ ...options, mr: options.mr || mrUrl }));


program.parse();


