const path = require('node:path');
const fs = require('fs-extra');
const kleur = require('kleur');
const ui = require('../utils/ui');
const { printCompactHeader } = require('../utils/brand');
const { createTranslator, detectDefaultLanguage } = require('../utils/i18n');
const { inspectPng } = require('./splash');
const { runFlutterLauncherIcons } = require('./icon');

const ASSETS_DIR = path.join('assets', 'images');
const FAVICON_NAME = 'favicon.png';

async function assertKasyProject(projectDir, t) {
  const kitSetupPath = path.join(projectDir, 'kit_setup.json');
  const pubspecPath = path.join(projectDir, 'pubspec.yaml');
  if (!(await fs.pathExists(kitSetupPath)) && !(await fs.pathExists(pubspecPath))) {
    throw new Error(t('favicon.error.notKasyProject'));
  }
  const assetsDir = path.join(projectDir, ASSETS_DIR);
  await fs.ensureDir(assetsDir);
}

function resolveInputPath(flagValue) {
  if (!flagValue) return null;
  const expanded = flagValue.startsWith('~')
    ? path.join(require('node:os').homedir(), flagValue.slice(1))
    : flagValue;
  return path.resolve(expanded);
}

async function runFavicon(projectDir, options = {}) {
  const language = options.language || detectDefaultLanguage();
  const t = createTranslator(language);

  printCompactHeader();
  ui.intro(kleur.bold().cyan(t('favicon.intro')));

  await assertKasyProject(projectDir, t);

  const imagePath = resolveInputPath(options.image);

  if (!imagePath) {
    ui.log.error(t('favicon.error.imageRequired'));
    ui.log.message(kleur.dim('kasy favicon --image <favicon.png>'));
    process.exit(1);
  }

  if (!(await fs.pathExists(imagePath))) {
    ui.log.error(t('favicon.error.fileNotFound', { path: imagePath }));
    process.exit(1);
  }

  const inspectSpinner = ui.spinner();
  inspectSpinner.start(t('favicon.validating'));

  let info;
  try {
    info = await inspectPng(imagePath);
  } catch (err) {
    inspectSpinner.stop(`✖ ${err.message || t('favicon.error.notPng')}`);
    process.exit(1);
  }

  if (!info.valid) {
    inspectSpinner.stop(`✖ ${t('favicon.error.notPng')}`);
    process.exit(1);
  }

  inspectSpinner.stop(t('favicon.validated'));

  const warnings = [];
  if (info.width !== info.height) {
    warnings.push(t('favicon.warn.notSquare', { w: info.width, h: info.height }));
  }
  if (info.width < 512 || info.height < 512) {
    warnings.push(t('favicon.warn.small', { w: info.width, h: info.height }));
  }
  if (warnings.length > 0) {
    ui.note(warnings.map((w) => `${kleur.yellow('⚠')} ${w}`).join('\n'), t('favicon.warn.title'));
  }

  const dest = path.join(projectDir, ASSETS_DIR, FAVICON_NAME);

  const copySpinner = ui.spinner();
  copySpinner.start(t('favicon.copying'));
  await fs.copy(imagePath, dest, { overwrite: true });
  copySpinner.stop(t('favicon.copied'));

  if (options.skipGenerate) {
    ui.note(t('favicon.skipGenerate.hint'), t('favicon.skipGenerate.title'));
    ui.outro(t('favicon.done'));
    return;
  }

  const genSpinner = ui.spinner();
  genSpinner.start(t('favicon.generating'));
  const result = await runFlutterLauncherIcons(projectDir);
  if (result.ok) {
    genSpinner.stop(t('favicon.generated'));
  } else {
    genSpinner.stop(`⚠ ${t('favicon.error.generateFailed')}`);
    if (result.stderr) {
      ui.log.message(kleur.dim(result.stderr.split('\n').slice(0, 8).join('\n')));
    }
    ui.log.message(kleur.dim('dart run flutter_launcher_icons'));
    process.exit(1);
  }

  const summary = `${kleur.bold(t('favicon.summary.favicon'))}: ${kleur.white(FAVICON_NAME)} (${info.width}x${info.height})`;
  ui.note(summary, t('favicon.summary.title'));

  ui.outro(t('favicon.done'));
}

module.exports = { runFavicon };
