'use strict';

const path = require('node:path');
const kleur = require('kleur');
const ui = require('../utils/ui');
const { printCompactHeader } = require('../utils/brand');
const { createTranslator, detectDefaultLanguage } = require('../utils/i18n');
const { isKasyFlutterProject, openUrl } = require('../utils/apple-release');
const { validateGoogleIosUrlScheme } = require('../scaffold/shared/post-build');
const {
  codemagicReleaseDocPath,
  writeCodemagicEnv,
  validateCodemagicSetup,
  triggerBuild,
  getBuildStatus,
  URL_CODEMAGIC_APPS,
  URL_CODEMAGIC_API,
} = require('../utils/codemagic-release');

async function assertProject(projectDir, t) {
  if (!(await isKasyFlutterProject(projectDir))) {
    throw new Error(t('codemagic.error.notProject'));
  }
}

async function runConfigure(directory, options = {}) {
  const lang = options.language || detectDefaultLanguage();
  const t = createTranslator(lang);
  const projectDir = path.resolve(directory || '.');

  await assertProject(projectDir, t);

  printCompactHeader(t);
  ui.intro(t('codemagic.configure.title'));
  ui.log.message(kleur.dim(`${t('codemagic.configure.doc')}: ${codemagicReleaseDocPath(lang)}`));
  ui.log.warn(t('codemagic.configure.checklist'));

  ui.log.info(t('codemagic.configure.openingLinks'));
  openUrl(URL_CODEMAGIC_API);
  openUrl(URL_CODEMAGIC_APPS);

  const cancel = () => { ui.cancel(t('codemagic.configure.cancelled')); process.exit(0); };
  const required = (v) => (v && String(v).trim().length > 0 ? undefined : t('codemagic.configure.q.required'));

  const token = await ui.password({
    message: t('codemagic.configure.q.token'),
    validate: required,
    onCancel: cancel,
  });
  const appId = await ui.text({
    message: t('codemagic.configure.q.appId'),
    validate: required,
    onCancel: cancel,
  });
  const workflowId = await ui.text({
    message: t('codemagic.configure.q.workflowId'),
    initialValue: 'ios-workflow',
    onCancel: cancel,
  });
  const branch = await ui.text({
    message: t('codemagic.configure.q.branch'),
    initialValue: 'main',
    onCancel: cancel,
  });

  await writeCodemagicEnv(projectDir, {
    token: String(token).trim(),
    appId: String(appId).trim(),
    workflowId: String(workflowId).trim() || 'ios-workflow',
    branch: String(branch).trim() || 'main',
  });

  ui.log.success(t('codemagic.configure.success'));
  ui.outro(kleur.cyan(`${t('codemagic.configure.next')}: kasy codemagic release`));
}

async function runRelease(directory, options = {}) {
  const t = createTranslator(options.language || detectDefaultLanguage());
  const projectDir = path.resolve(directory || '.');

  await assertProject(projectDir, t);

  const validation = await validateCodemagicSetup(projectDir);
  if (!validation.ok) {
    printCompactHeader(t);
    ui.log.error(t('codemagic.error.notConfigured'));
    if (validation.issues.includes('missing_yaml')) {
      ui.log.message(kleur.dim(t('codemagic.error.addCi')));
    }
    if (validation.issues.includes('missing_env')) {
      ui.log.message(kleur.dim(t('codemagic.error.runConfigure')));
    }
    process.exitCode = 1;
    return;
  }

  const googleScheme = await validateGoogleIosUrlScheme(projectDir);
  if (!googleScheme.ok) {
    printCompactHeader(t);
    ui.log.error(t('codemagic.error.googleUrlScheme'));
    ui.log.message(kleur.dim(googleScheme.error));
    ui.log.info(t('ios.error.googleUrlSchemeHint'));
    process.exitCode = 1;
    return;
  }

  printCompactHeader(t);
  ui.intro(t('codemagic.release.title'));

  const spinner = ui.spinner();
  spinner.start(t('codemagic.release.spin'));
  try {
    const result = await triggerBuild(projectDir, validation.env);
    spinner.stop(t('codemagic.release.spinDone'));
    const buildId = result.buildId || result._id;
    if (buildId) {
      ui.log.success(t('codemagic.release.triggered'));
      ui.log.info(`Build ID: ${kleur.cyan(buildId)}`);
      ui.log.message(kleur.dim(`https://codemagic.io/builds/${buildId}`));
      ui.outro('');
    } else {
      ui.outro(t('codemagic.release.triggered'));
    }
  } catch (err) {
    spinner.stop(err.message, 2);
    process.exitCode = 1;
  }
}

async function runStatus(buildId, directory, options = {}) {
  const t = createTranslator(options.language || detectDefaultLanguage());
  const projectDir = path.resolve(directory || '.');

  await assertProject(projectDir, t);

  const validation = await validateCodemagicSetup(projectDir);
  if (!validation.env?.CODEMAGIC_API_TOKEN) {
    printCompactHeader(t);
    ui.log.error(t('codemagic.error.runConfigure'));
    process.exitCode = 1;
    return;
  }

  if (!buildId) {
    printCompactHeader(t);
    ui.log.warn(t('codemagic.status.usage'));
    process.exitCode = 1;
    return;
  }

  printCompactHeader(t);
  ui.intro(`${t('codemagic.status.title')}: ${buildId}`);

  const spinner = ui.spinner();
  spinner.start(t('codemagic.status.spin'));
  try {
    const result = await getBuildStatus(buildId, validation.env.CODEMAGIC_API_TOKEN);
    spinner.stop(t('codemagic.status.spinDone'));
    ui.note(JSON.stringify(result, null, 2));
    ui.outro('');
  } catch (err) {
    spinner.stop(err.message, 2);
    process.exitCode = 1;
  }
}

module.exports = {
  runConfigure,
  runRelease,
  runStatus,
};
