/**
 * Map common errors to actionable hints for non-technical users.
 *
 * Pattern: takes an Error and the current translator (t), returns a string
 * with both the original message and a one-line "→ try this" suggestion.
 * Falls back to just the message when no pattern matches.
 *
 * Used by bin/kasy.js global error handler.
 */

'use strict';

const kleur = require('kleur');

// Each rule: { match: RegExp | (err) => boolean, hintKey: i18n key, hintFallback: english fallback }
// Order matters — more specific rules first.
const RULES = [
  {
    match: /pubspec\.yaml/i,
    hintKey: 'error.hint.notFlutterProject',
    hintFallback: 'You\'re not inside a Flutter project. Try `kasy new` to create one, or cd into an existing one.',
  },
  {
    match: /flutter[^a-z]+not found|ENOENT.*flutter/i,
    hintKey: 'error.hint.flutterMissing',
    hintFallback: 'Flutter is not installed or not on your PATH. Run `kasy doctor` to diagnose.',
  },
  {
    match: /EACCES|permission denied/i,
    hintKey: 'error.hint.permission',
    hintFallback: 'A file or folder is read-only. Check the parent directory permissions or try again from your home folder.',
  },
  {
    match: /ENOSPC|No space left/i,
    hintKey: 'error.hint.noSpace',
    hintFallback: 'Disk is full. Free up space (Flutter/Xcode builds need 5-15 GB) and try again.',
  },
  {
    match: /ECONNREFUSED|ENOTFOUND|getaddrinfo|network/i,
    hintKey: 'error.hint.network',
    hintFallback: 'Network problem — check your internet connection and try again.',
  },
  {
    match: /firebase.*not.*log(ged|in)|firebase login/i,
    hintKey: 'error.hint.firebaseLogin',
    hintFallback: 'You are not logged into Firebase. Run: firebase login',
  },
  {
    match: /supabase.*not.*log(ged|in)|supabase login/i,
    hintKey: 'error.hint.supabaseLogin',
    hintFallback: 'You are not logged into Supabase. Run: supabase login',
  },
  {
    match: /gcloud.*not authenticated|gcloud auth/i,
    hintKey: 'error.hint.gcloudAuth',
    hintFallback: 'You need to authenticate with gcloud. Run: gcloud auth login',
  },
  {
    match: /flutter run exited|flutter exited/i,
    hintKey: 'error.hint.flutterRunFailed',
    hintFallback: 'Flutter could not run the app. Run again with --verbose to see the full Flutter output.',
  },
];

function findHint(message) {
  const text = String(message || '');
  for (const rule of RULES) {
    const isMatch = typeof rule.match === 'function' ? rule.match({ message: text }) : rule.match.test(text);
    if (isMatch) return rule;
  }
  return null;
}

/**
 * Format an error for terminal output. Returns a string with the red ✗ line
 * plus, when we recognize the pattern, a dim hint line beneath it.
 */
function formatError(err, t) {
  const message = err && err.message ? err.message : String(err);
  const lines = [kleur.red(`\n✗ ${message}`)];
  const hint = findHint(message);
  if (hint) {
    const text = t ? t(hint.hintKey) : null;
    // Translator returns the key itself when missing — fall back to English.
    const hintText = (text && text !== hint.hintKey) ? text : hint.hintFallback;
    lines.push(kleur.dim(`  → ${hintText}`));
  }
  return lines.join('\n');
}

module.exports = { formatError, findHint };
