import 'server-only'

import { REGIONS } from '../data/regions'
import type { CurrentUser } from '../auth/current-user'
import type { Locale } from '../domain/enums'
import { riskToState } from '../domain/enums'
import { environmentFor, resourcesFor } from '../engine/grid'
import { predictFailure } from '../engine/prediction'
import { evaluateCandidates, generateCandidates } from '../engine/actions'
import { factorLabel } from '../engine/explain'
import { round } from '../engine/rng'
import { getGridSnapshot } from './grid-service'
import { getLoadForecast, getRenewableIntelligence } from './forecast-service'
import { runScenarioSimulation } from './simulation-service'
import { analyseAsset, futureBranches, pickFocusAsset } from './intelligence-service'
import { runCounterfactual } from './counterfactual-service'
import { getWeakLinkAnalysis } from './stress-service'
import { listHunts } from './risk-hunter-service'
import { listProofs } from './proof-service'

/**
 * NABDH Copilot (§12).
 *
 * A deliberately *non-generative* assistant: it classifies a question into one of a
 * fixed set of intents, extracts the entities it needs, and answers by querying the same
 * engines the rest of the console uses. That choice is the point — the answers are
 * traceable to a computation rather than produced by a language model, it works with no
 * network access, and it cannot invent a megawatt figure.
 *
 * Every answer is scoped by the caller's permissions, so the Copilot can never become a
 * side channel around role-based access control.
 */

export type CopilotIntent =
  | 'riskiest_region'
  | 'why_risk'
  | 'failing_assets'
  | 'what_if'
  | 'reduce_risk'
  | 'critical_assets'
  | 'compare_regions'
  | 'run_scenario'
  | 'grid_status'
  | 'forecast'
  | 'renewables'
  | 'asset_detail'
  | 'riskiest_asset'
  | 'cascade_impact'
  | 'minimum_action'
  | 'compare_strategies'
  | 'worst_case'
  | 'weakest_link'
  | 'root_cause'
  | 'hunt_risks'
  | 'prove_it'
  | 'unknown'

export interface CopilotFact {
  label: string
  value: string
  tone?: 'normal' | 'warning' | 'critical'
}

export interface CopilotAnswer {
  intent: CopilotIntent
  answer: string
  facts: CopilotFact[]
  links: Array<{ label: string; href: string }>
  /** What the answer was computed from, so the operator can check it. */
  basedOn: string
  permissionDenied?: boolean
}

interface Entities {
  regionCodes: string[]
  assetCode: string | null
  deltaPct: number | null
  hours: number | null
}

// ─────────────────────────────────────────────────────────────────────────────
// Interpretation
// ─────────────────────────────────────────────────────────────────────────────

const INTENT_PATTERNS: Array<{ intent: CopilotIntent; patterns: RegExp[] }> = [
  {
    intent: 'cascade_impact',
    patterns: [
      /cascad/i,
      /domino/i,
      /knock[- ]?on/i,
      /ripple/i,
      /دومينو/,
      /تأثير\s+تعطل/,
      /سلسلة\s+(?:تأثير|الأعطال)/,
      /الأعطال\s+المتتالية/,
    ],
  },
  {
    intent: 'minimum_action',
    patterns: [
      /minimum\s+(?:intervention|action|change)/i,
      /smallest\s+(?:change|action)/i,
      /least\s+(?:action|intervention)/i,
      /what\s+needs\s+to\s+change/i,
      /أقل\s+(?:إجراء|تدخل|تغيير)/,
      /ما\s+الذي\s+يجب\s+أن\s+يتغير/,
    ],
  },
  {
    intent: 'compare_strategies',
    patterns: [
      /compare\s+(?:\d+\s+)?strateg/i,
      /which\s+strategy/i,
      /قارن\s+(?:\d+\s+)?(?:استراتيجيات|الاستراتيجيات)/,
      /أي\s+استراتيجية/,
    ],
  },
  {
    intent: 'worst_case',
    patterns: [
      /worst[- ]?case/i,
      /worst\s+scenario/i,
      /أسوأ\s+(?:سيناريو|حالة|الحالات)/,
    ],
  },
  {
    intent: 'weakest_link',
    patterns: [
      /weakest\s+(?:link|asset|point)/i,
      /most\s+fragile/i,
      /الحلقة\s+الأضعف/,
      /أضعف\s+(?:نقطة|أصل|حلقة)/,
    ],
  },
  {
    intent: 'riskiest_asset',
    patterns: [
      /(?:most|highest)\s+(?:dangerous|at[- ]risk)\s+asset/i,
      /riskiest\s+asset/i,
      /which\s+asset\s+is\s+(?:the\s+)?(?:most|worst)/i,
      /أخطر\s+(?:أصل|محول|وحدة)/,
      /أي\s+أصل\s+(?:هو\s+)?الأخطر/,
    ],
  },
  {
    // Placed before root_cause: "what risks are hidden" contains no root-cause wording, but
    // keeping the two adjacent makes the ordering deliberate rather than incidental.
    intent: 'hunt_risks',
    patterns: [
      /hidden\s+risk/i,
      /(?:hunt|search)\s+for\s+risk/i,
      /what\s+(?:risks?|failures?)\s+(?:am\s+i|are\s+we)\s+(?:missing|not\s+seeing)/i,
      /risk\s+hunter/i,
      /مخاطر\s+(?:خفية|مخفية)/,
      /صائد\s+المخاطر/,
      /ما\s+الذي\s+(?:لا\s+)?(?:أراه|نراه|فاتنا)/,
    ],
  },
  {
    intent: 'prove_it',
    patterns: [
      /prove\s+it/i,
      /why\s+should\s+i\s+(?:believe|trust)\s+(?:this|that|it)/i,
      /show\s+(?:me\s+)?(?:the\s+)?(?:proof|evidence\s+bundle)/i,
      /replay\s+(?:the\s+)?decision/i,
      /أثبت\s+ذلك/,
      /لماذا\s+(?:أصدق|نصدق)/,
      /(?:أعد|إعادة)\s+تشغيل\s+القرار/,
    ],
  },
  {
    intent: 'root_cause',
    patterns: [
      /root\s+cause/i,
      /why\s+is\s+(?:the\s+)?risk\s+(?:rising|up|high)/i,
      /السبب\s+الجذري/,
      /سبب\s+ارتفاع\s+(?:الخطر|المخاطر)/,
    ],
  },
  {
    intent: 'what_if',
    patterns: [
      /what\s+(?:happens|if)/i,
      /ماذا\s+(?:يحدث|لو)/,
      /إذا\s+(?:زاد|ارتفع|انخفض)/,
      /لو\s+(?:زاد|ارتفع)/,
    ],
  },
  {
    intent: 'run_scenario',
    patterns: [/run\s+(?:a\s+)?(?:heat|scenario)/i, /شغّ?ل\s+سيناريو/, /سيناريو\s+موجة/],
  },
  {
    intent: 'why_risk',
    patterns: [/\bwhy\b/i, /لماذا/, /ما\s+سبب/, /سبب\s+ارتفاع/],
  },
  {
    intent: 'reduce_risk',
    patterns: [
      /how\s+(?:do|can)\s+i?\s*reduce/i,
      /reduce\s+(?:the\s+)?risk/i,
      /كيف\s+أ?خفض/,
      /تقليل\s+المخاطر/,
    ],
  },
  {
    intent: 'compare_regions',
    patterns: [/compare/i, /قارن/, /مقارنة/],
  },
  {
    intent: 'failing_assets',
    patterns: [
      /might\s+fail/i,
      /expected\s+to\s+fail/i,
      /which\s+transformers/i,
      /متوقع\s+تعطل/,
      /ستتعطل/,
      /المحولات\s+المتوقع/,
    ],
  },
  {
    intent: 'critical_assets',
    patterns: [/critical\s+assets/i, /show\s+me\s+all/i, /الأصول\s+الحرجة/, /اعرض\s+لي/],
  },
  {
    intent: 'riskiest_region',
    patterns: [
      /most\s+at\s+risk/i,
      /riskiest/i,
      /highest\s+risk/i,
      /أخطر\s+منطقة/,
      /أكثر\s+المناطق/,
      /أعلى\s+خطر/,
    ],
  },
  {
    intent: 'forecast',
    patterns: [/forecast/i, /peak/i, /توقع/, /الذروة/, /الأحمال\s+المتوقعة/],
  },
  {
    intent: 'renewables',
    patterns: [/solar/i, /wind/i, /renewable/i, /الشمسية/, /الرياح/, /المتجددة/],
  },
  {
    intent: 'grid_status',
    patterns: [/grid\s+status/i, /stability/i, /how\s+is\s+the\s+grid/i, /حالة\s+الشبكة/, /الاستقرار/],
  },
]

function extractEntities(question: string): Entities {
  const regionCodes: string[] = []
  for (const region of REGIONS) {
    const needles = [region.name.toLowerCase(), region.nameAr, region.code.toLowerCase()]
    if (needles.some((needle) => question.toLowerCase().includes(needle))) {
      regionCodes.push(region.code)
    }
  }

  const assetMatch = question.match(/\b([A-Z]{2,3}-\d{2,4})\b/i)
  const percentMatch = question.match(/(\d{1,3})\s*(?:%|٪|percent|بالمئة|في\s*المئة)/)
  const hoursMatch = question.match(/(\d{1,2})\s*(?:hours?|h\b|ساعة|ساعات|ساعتين)/i)

  return {
    regionCodes,
    assetCode: assetMatch ? assetMatch[1].toUpperCase() : null,
    deltaPct: percentMatch ? Number(percentMatch[1]) : null,
    // "ساعتين" is the Arabic dual — two hours — and carries no digit to match.
    hours: hoursMatch ? Number(hoursMatch[1]) : /ساعتين/.test(question) ? 2 : null,
  }
}

export function interpret(question: string): { intent: CopilotIntent; entities: Entities } {
  const entities = extractEntities(question)
  for (const candidate of INTENT_PATTERNS) {
    if (!candidate.patterns.some((pattern) => pattern.test(question))) continue

    // Root Cause AI reasons about one asset. "Why is risk rising in Riyadh" names a
    // region and no asset, and the honest answer to that is the regional breakdown —
    // picking the region's worst asset and explaining *it* would answer a question the
    // operator did not ask.
    if (
      candidate.intent === 'root_cause' &&
      entities.assetCode === null &&
      entities.regionCodes.length > 0
    ) {
      return { intent: 'why_risk', entities }
    }

    return { intent: candidate.intent, entities }
  }
  if (entities.assetCode) return { intent: 'asset_detail', entities }
  if (entities.regionCodes.length >= 2) return { intent: 'compare_regions', entities }
  if (entities.regionCodes.length === 1) return { intent: 'why_risk', entities }
  return { intent: 'unknown', entities }
}

// ─────────────────────────────────────────────────────────────────────────────
// Answering
// ─────────────────────────────────────────────────────────────────────────────

function regionName(code: string, locale: Locale): string {
  const region = REGIONS.find((entry) => entry.code === code)
  if (!region) return code
  return locale === 'ar' ? region.nameAr : region.name
}

function pct(value: number): string {
  return `${round(value, 0)}%`
}

function requires(user: CurrentUser, permission: string, locale: Locale): CopilotAnswer | null {
  if (user.permissions.has(permission)) return null
  return {
    intent: 'unknown',
    answer:
      locale === 'ar'
        ? 'لا تملك صلاحية الاطلاع على هذه البيانات، ولا يستطيع المساعد تجاوز الصلاحيات.'
        : 'Your role does not grant access to that data, and the Copilot cannot work around permissions.',
    facts: [],
    links: [],
    basedOn: locale === 'ar' ? 'التحقق من الصلاحيات' : 'Permission check',
    permissionDenied: true,
  }
}

export async function answerQuestion(
  question: string,
  user: CurrentUser,
  locale: Locale,
): Promise<CopilotAnswer> {
  const { intent, entities } = interpret(question)
  const ar = locale === 'ar'

  /**
   * Returned both when nothing matched and when a matched intent could not complete —
   * an unknown asset code, say. A handler that cannot answer breaks out of the switch
   * rather than inventing a reply, and lands here.
   */
  const fallback: CopilotAnswer = {
    intent: 'unknown',
    answer: ar
      ? 'لم أتمكن من ربط سؤالك بتحليل أستطيع تنفيذه. جرّب سؤالًا عن أخطر منطقة، أو سبب ارتفاع الخطر، أو ماذا يحدث إذا زاد الحمل.'
      : 'I could not map that to an analysis I can run. Try asking which region is most at risk, why risk is rising, or what happens if load increases.',
    facts: [],
    links: [
      { label: ar ? 'مركز القيادة' : 'Command Center', href: '/command-center' },
      { label: ar ? 'التنبؤات' : 'Predictions', href: '/predictions' },
    ],
    basedOn: ar ? 'مطابقة النوايا' : 'Intent matching',
  }

  switch (intent) {
    case 'riskiest_region': {
      const denied = requires(user, 'grid.read', locale)
      if (denied) return denied

      const snapshot = await getGridSnapshot()
      const ranked = [...snapshot.regions].sort((a, b) => b.peakRisk - a.peakRisk)
      const top = ranked[0]
      const state = riskToState(top.peakRisk)

      return {
        intent,
        answer: ar
          ? `أعلى منطقة خطرًا الآن هي ${top.nameAr} بأقصى درجة خطر ${pct(top.peakRisk)} (${top.assetsAtRisk} أصلًا فوق عتبة المراقبة من أصل ${top.assetCount}). حملها الحالي ${round(top.loadMw, 0)} ميجاواط وهامش الاحتياطي ${pct(top.reserveMarginPct)}.`
          : `${top.name} carries the highest risk right now, peaking at ${pct(top.peakRisk)} with ${top.assetsAtRisk} of ${top.assetCount} assets above the watch threshold. Its load is ${round(top.loadMw, 0)} MW against a ${pct(top.reserveMarginPct)} reserve margin.`,
        facts: ranked.slice(0, 5).map((region) => ({
          label: ar ? region.nameAr : region.name,
          value: pct(region.peakRisk),
          tone: region.peakRisk >= 75 ? 'critical' : region.peakRisk >= 55 ? 'warning' : 'normal',
        })),
        links: [
          { label: ar ? 'الخريطة الوطنية' : 'National map', href: `/map?region=${top.code}` },
          { label: ar ? 'حالة الشبكة' : 'Grid status', href: '/grid' },
        ],
        basedOn: ar
          ? `لقطة الشبكة الحية · ${state}`
          : `Live grid snapshot · ${state}`,
      }
    }

    case 'why_risk': {
      const denied = requires(user, 'predictions.read', locale)
      if (denied) return denied

      const snapshot = await getGridSnapshot()
      const scope = entities.regionCodes.length
        ? snapshot.assets.filter((asset) => entities.regionCodes.includes(asset.profile.regionCode))
        : snapshot.assets
      const target = [...scope].sort((a, b) => b.risk.score - a.risk.score)[0]

      if (!target) {
        return {
          intent,
          answer: ar ? 'لا توجد أصول ضمن النطاق المطلوب.' : 'No assets match that scope.',
          facts: [],
          links: [],
          basedOn: ar ? 'لقطة الشبكة الحية' : 'Live grid snapshot',
        }
      }

      const factors = target.risk.topFactors.slice(0, 4)
      const where = entities.regionCodes.length
        ? regionName(entities.regionCodes[0], locale)
        : regionName(target.profile.regionCode, locale)

      return {
        intent,
        answer: ar
          ? `أعلى مساهم في المخاطر ضمن ${where} هو ${target.profile.code} بدرجة خطر ${pct(target.risk.score)}. تتكوّن الدرجة من: ${factors.map((factor) => `${factorLabel(factor.key, locale)} (${round(factor.contribution, 1)} نقطة)`).join('، ')}. التحميل ${pct(target.sample.loadPct)} والحرارة ${round(target.sample.tempC, 0)} مئوية.`
          : `The largest contributor in ${where} is ${target.profile.code} at ${pct(target.risk.score)} risk. That score decomposes into: ${factors.map((factor) => `${factorLabel(factor.key, locale)} (${round(factor.contribution, 1)} pts)`).join(', ')}. It is running at ${pct(target.sample.loadPct)} loading and ${round(target.sample.tempC, 0)} °C.`,
        facts: factors.map((factor) => ({
          label: factorLabel(factor.key, locale),
          value: `+${round(factor.contribution, 1)}`,
          tone: factor.contribution > 15 ? 'critical' : factor.contribution > 6 ? 'warning' : 'normal',
        })),
        links: [
          {
            label: ar ? 'فتح الأصل' : 'Open asset',
            href: `/assets/${encodeURIComponent(target.profile.code)}`,
          },
        ],
        basedOn: ar ? 'محرك الخطر · تفكيك العوامل' : 'Risk engine · factor decomposition',
      }
    }

    case 'failing_assets': {
      const denied = requires(user, 'predictions.read', locale)
      if (denied) return denied

      const horizonMin = (entities.hours ?? 2) * 60
      const snapshot = await getGridSnapshot()
      const scope = entities.regionCodes.length
        ? snapshot.assets.filter((asset) => entities.regionCodes.includes(asset.profile.regionCode))
        : snapshot.assets

      const candidates = [...scope].sort((a, b) => b.risk.score - a.risk.score).slice(0, 8)

      const predicted = candidates
        .map((candidate) => {
          const region = REGIONS.find((entry) => entry.code === candidate.profile.regionCode)!
          const envAt = environmentFor(region, {})
          const prediction = predictFailure(candidate.profile, snapshot.ts, envAt, {
            dnaSimilarity: candidate.dnaSimilarity,
            neighbourStress: candidate.neighbourStress,
            horizonMin,
            stepMin: 10,
          })
          return { candidate, prediction }
        })
        .filter((entry) => entry.prediction.etaMinutes !== null)
        .sort((a, b) => (a.prediction.etaMinutes ?? 0) - (b.prediction.etaMinutes ?? 0))

      if (predicted.length === 0) {
        return {
          intent,
          answer: ar
            ? `لا يُتوقع تجاوز أي حد تشغيلي خلال ${entities.hours ?? 2} ساعة ضمن النطاق المطلوب. أعلى خطر حالي ${pct(candidates[0]?.risk.score ?? 0)} على ${candidates[0]?.profile.code ?? '—'}.`
            : `No operating limit is crossed within ${entities.hours ?? 2} hours in that scope. The highest current risk is ${pct(candidates[0]?.risk.score ?? 0)} on ${candidates[0]?.profile.code ?? '—'}.`,
          facts: candidates.slice(0, 5).map((entry) => ({
            label: entry.profile.code,
            value: pct(entry.risk.score),
            tone: entry.risk.score >= 55 ? 'warning' : 'normal',
          })),
          links: [{ label: ar ? 'التنبؤات' : 'Predictions', href: '/predictions' }],
          basedOn: ar ? 'المسح المستقبلي للتوأم الرقمي' : 'Digital-twin forward walk',
        }
      }

      return {
        intent,
        answer: ar
          ? `${predicted.length} أصل يتجاوز حدًا تشغيليًا خلال ${entities.hours ?? 2} ساعة. الأقرب هو ${predicted[0].candidate.profile.code} خلال ${predicted[0].prediction.etaMinutes} دقيقة (${pct(predicted[0].prediction.probability * 100)} احتمالية).`
          : `${predicted.length} asset(s) cross an operating limit within ${entities.hours ?? 2} hours. The nearest is ${predicted[0].candidate.profile.code} in ${predicted[0].prediction.etaMinutes} minutes at ${pct(predicted[0].prediction.probability * 100)} probability.`,
        facts: predicted.slice(0, 5).map((entry) => ({
          label: entry.candidate.profile.code,
          value: `${entry.prediction.etaMinutes} ${ar ? 'دقيقة' : 'min'}`,
          tone: (entry.prediction.etaMinutes ?? 0) < 60 ? 'critical' : 'warning',
        })),
        links: [
          { label: ar ? 'التنبؤات' : 'Predictions', href: '/predictions' },
          {
            label: ar ? 'آلة الزمن' : 'Time Machine',
            href: `/time-machine?asset=${encodeURIComponent(predicted[0].candidate.profile.code)}`,
          },
        ],
        basedOn: ar ? 'المسح المستقبلي للتوأم الرقمي' : 'Digital-twin forward walk',
      }
    }

    case 'what_if':
    case 'run_scenario': {
      const denied = requires(user, 'simulations.run', locale)
      if (denied) return denied

      const isHeat = /heat|حر|حرارة/i.test(question)
      const delta = entities.deltaPct ?? (isHeat ? 0 : 25)
      const params = {
        loadDeltaPct: isHeat ? 0 : delta,
        tempDeltaC: isHeat ? 6 : 0,
        regionCode: entities.regionCodes[0] ?? null,
        durationMin: 120,
      }

      const outcome = await runScenarioSimulation({
        params,
        name: isHeat ? 'Copilot — heat wave' : `Copilot — load +${delta}%`,
        nameAr: isHeat ? 'المساعد — موجة حر' : `المساعد — زيادة الحمل ${delta}٪`,
        userId: user.id,
      })

      const where = entities.regionCodes.length
        ? regionName(entities.regionCodes[0], locale)
        : ar
          ? 'على المستوى الوطني'
          : 'nationally'

      return {
        intent,
        answer: ar
          ? `شغّلت المحاكاة ${where}. ترتفع أقصى درجة خطر من ${pct(outcome.riskBefore)} إلى ${pct(outcome.riskAfter)}، ويتغير الحمل من ${round(outcome.loadBeforeMw, 0)} إلى ${round(outcome.loadAfterMw, 0)} ميجاواط، ويتأثر ${outcome.regionsAffected} من المناطق. ${outcome.verdictAr}`
          : `I ran that simulation ${where}. Peak risk moves from ${pct(outcome.riskBefore)} to ${pct(outcome.riskAfter)}, load from ${round(outcome.loadBeforeMw, 0)} to ${round(outcome.loadAfterMw, 0)} MW, and ${outcome.regionsAffected} region(s) are affected. ${outcome.verdict}`,
        facts: [
          {
            label: ar ? 'الخطر' : 'Risk',
            value: `${pct(outcome.riskBefore)} → ${pct(outcome.riskAfter)}`,
            tone: outcome.riskAfter >= 75 ? 'critical' : outcome.riskAfter >= 55 ? 'warning' : 'normal',
          },
          {
            label: ar ? 'الحمل' : 'Load',
            value: `${round(outcome.loadBeforeMw, 0)} → ${round(outcome.loadAfterMw, 0)} MW`,
          },
          {
            label: ar ? 'الاستقرار' : 'Stability',
            value: `${round(outcome.stabilityBefore, 1)} → ${round(outcome.stabilityAfter, 1)}`,
          },
          {
            label: ar ? 'المشتركون' : 'Customers',
            value: String(outcome.customersImpacted),
            tone: outcome.customersImpacted > 0 ? 'critical' : 'normal',
          },
        ],
        links: [
          { label: ar ? 'المحاكاة' : 'Simulations', href: '/simulations' },
          { label: ar ? 'السيناريوهات' : 'Scenarios', href: '/scenarios' },
        ],
        basedOn: ar ? `محاكاة ${outcome.code}` : `Simulation ${outcome.code}`,
      }
    }

    case 'reduce_risk': {
      const denied = requires(user, 'recommendations.read', locale)
      if (denied) return denied

      const snapshot = await getGridSnapshot()
      const scope = entities.regionCodes.length
        ? snapshot.assets.filter((asset) => entities.regionCodes.includes(asset.profile.regionCode))
        : snapshot.assets
      const target = [...scope].sort((a, b) => b.risk.score - a.risk.score)[0]

      if (!target) {
        return {
          intent,
          answer: ar ? 'لا توجد أصول ضمن النطاق.' : 'No assets in that scope.',
          facts: [],
          links: [],
          basedOn: ar ? 'لقطة الشبكة الحية' : 'Live grid snapshot',
        }
      }

      const region = REGIONS.find((entry) => entry.code === target.profile.regionCode)!
      const envAt = environmentFor(region, {})
      const prediction = predictFailure(target.profile, snapshot.ts, envAt, {
        dnaSimilarity: target.dnaSimilarity,
        neighbourStress: target.neighbourStress,
        horizonMin: 180,
        stepMin: 10,
      })
      const context = {
        profile: target.profile,
        ts: snapshot.ts,
        envAt,
        dnaSimilarity: target.dnaSimilarity,
        neighbourStress: target.neighbourStress,
        resources: resourcesFor(target.profile, snapshot.assets),
        evaluateAtMin: prediction.etaMinutes ?? 45,
      }
      const actions = evaluateCandidates(context, generateCandidates(context)).filter(
        (action) => action.riskReduction > 0.05,
      )

      if (actions.length === 0) {
        return {
          intent,
          answer: ar
            ? `${target.profile.code} عند ${pct(target.risk.score)} ولا يوجد إجراء وقائي مطلوب عند هذا المستوى.`
            : `${target.profile.code} is at ${pct(target.risk.score)} and needs no preventive action at this level.`,
          facts: [],
          links: [
            {
              label: ar ? 'فتح الأصل' : 'Open asset',
              href: `/assets/${encodeURIComponent(target.profile.code)}`,
            },
          ],
          basedOn: ar ? 'محرك التوصيات' : 'Recommendation engine',
        }
      }

      return {
        intent,
        answer: ar
          ? `أعلى الأصول خطرًا هو ${target.profile.code} عند ${pct(target.risk.score)}. أكثر الإجراءات أثرًا هو «${actions[0].titleAr}» بانخفاض متوقع قدره ${round(actions[0].riskReduction, 1)} نقطة. حاكِ الإجراء قبل اعتماده.`
          : `The highest-risk asset is ${target.profile.code} at ${pct(target.risk.score)}. The most effective action is "${actions[0].title}", worth ${round(actions[0].riskReduction, 1)} points. Simulate it before approving.`,
        facts: actions.slice(0, 4).map((action) => ({
          label: ar ? action.titleAr : action.title,
          value: `−${round(action.riskReduction, 1)}`,
          tone: 'normal',
        })),
        links: [
          {
            label: ar ? 'فتح الأصل' : 'Open asset',
            href: `/assets/${encodeURIComponent(target.profile.code)}`,
          },
        ],
        basedOn: ar ? 'محرك التوصيات · محاكاة التوأم' : 'Recommendation engine · twin simulation',
      }
    }

    case 'critical_assets': {
      const denied = requires(user, 'assets.read', locale)
      if (denied) return denied

      const snapshot = await getGridSnapshot()
      const critical = [...snapshot.assets]
        .filter((asset) => asset.risk.score >= 55)
        .sort((a, b) => b.risk.score - a.risk.score)

      return {
        intent,
        answer: ar
          ? critical.length === 0
            ? 'لا يوجد أصل فوق عتبة التحذير حاليًا. جميع الأصول ضمن نطاقها التشغيلي.'
            : `${critical.length} أصلًا فوق عتبة التحذير. الأعلى هو ${critical[0].profile.code} عند ${pct(critical[0].risk.score)}.`
          : critical.length === 0
            ? 'No asset is above the warning threshold. The whole fleet is inside its operating envelope.'
            : `${critical.length} asset(s) are above the warning threshold. The highest is ${critical[0].profile.code} at ${pct(critical[0].risk.score)}.`,
        facts: critical.slice(0, 8).map((asset) => ({
          label: `${asset.profile.code} · ${regionName(asset.profile.regionCode, locale)}`,
          value: pct(asset.risk.score),
          tone: asset.risk.score >= 75 ? 'critical' : 'warning',
        })),
        links: [{ label: ar ? 'الأصول' : 'Assets', href: '/assets' }],
        basedOn: ar ? 'لقطة الشبكة الحية' : 'Live grid snapshot',
      }
    }

    case 'compare_regions': {
      const denied = requires(user, 'grid.read', locale)
      if (denied) return denied

      const snapshot = await getGridSnapshot()
      const codes = entities.regionCodes.length >= 2
        ? entities.regionCodes.slice(0, 3)
        : [...snapshot.regions].sort((a, b) => b.peakRisk - a.peakRisk).slice(0, 2).map((r) => r.code)

      const chosen = codes
        .map((code) => snapshot.regions.find((region) => region.code === code))
        .filter((region): region is NonNullable<typeof region> => Boolean(region))

      return {
        intent,
        answer: ar
          ? chosen
              .map(
                (region) =>
                  `${region.nameAr}: حمل ${round(region.loadMw, 0)} ميجاواط، أقصى خطر ${pct(region.peakRisk)}، احتياطي ${pct(region.reserveMarginPct)}، ${region.assetsAtRisk} أصلًا معرّضًا.`,
              )
              .join(' ')
          : chosen
              .map(
                (region) =>
                  `${region.name}: ${round(region.loadMw, 0)} MW load, ${pct(region.peakRisk)} peak risk, ${pct(region.reserveMarginPct)} reserve, ${region.assetsAtRisk} assets at risk.`,
              )
              .join(' '),
        facts: chosen.flatMap((region) => [
          {
            label: `${ar ? region.nameAr : region.name} · ${ar ? 'الخطر' : 'risk'}`,
            value: pct(region.peakRisk),
            tone: region.peakRisk >= 75 ? ('critical' as const) : region.peakRisk >= 55 ? ('warning' as const) : ('normal' as const),
          },
          {
            label: `${ar ? region.nameAr : region.name} · ${ar ? 'الحمل' : 'load'}`,
            value: `${round(region.loadMw, 0)} MW`,
          },
        ]),
        links: [{ label: ar ? 'حالة الشبكة' : 'Grid status', href: '/grid' }],
        basedOn: ar ? 'لقطة الشبكة الحية' : 'Live grid snapshot',
      }
    }

    case 'forecast': {
      const denied = requires(user, 'forecast.read', locale)
      if (denied) return denied

      const forecast = await getLoadForecast(1440, entities.regionCodes[0] ?? null)
      const peakTime = new Date(forecast.peak.ts).toLocaleTimeString(ar ? 'ar-SA-u-nu-latn' : 'en-GB', {
        timeZone: 'Asia/Riyadh',
        hour: '2-digit',
        minute: '2-digit',
      })

      return {
        intent,
        answer: ar
          ? `الحمل الحالي ${round(forecast.currentMw, 0)} ميجاواط، والذروة المتوقعة ${round(forecast.peak.expectedMw, 0)} ميجاواط عند الساعة ${peakTime}. أدنى هامش احتياطي خلال الأفق ${pct(forecast.minReserveMarginPct)}.`
          : `Current load is ${round(forecast.currentMw, 0)} MW; the peak is forecast at ${round(forecast.peak.expectedMw, 0)} MW around ${peakTime}. The minimum reserve margin across the horizon is ${pct(forecast.minReserveMarginPct)}.`,
        facts: [
          { label: ar ? 'الحمل الحالي' : 'Current load', value: `${round(forecast.currentMw, 0)} MW` },
          { label: ar ? 'الذروة' : 'Peak', value: `${round(forecast.peak.expectedMw, 0)} MW` },
          { label: ar ? 'وقت الذروة' : 'Peak time', value: peakTime },
          {
            label: ar ? 'أدنى احتياطي' : 'Min reserve',
            value: pct(forecast.minReserveMarginPct),
            tone: forecast.minReserveMarginPct < 10 ? 'critical' : 'normal',
          },
        ],
        links: [{ label: ar ? 'توقع الأحمال' : 'Load forecast', href: '/forecast' }],
        basedOn: ar ? 'متنبئ الأحمال' : 'Load forecaster',
      }
    }

    case 'renewables': {
      const denied = requires(user, 'renewables.read', locale)
      if (denied) return denied

      const intelligence = await getRenewableIntelligence()
      return {
        intent,
        answer: ar
          ? `الإنتاج المتجدد الحالي ${round(intelligence.totalCurrentMw, 0)} ميجاواط من قدرة مركّبة ${round(intelligence.totalCapacityMw, 0)} ميجاواط. الشمسية ${round(intelligence.solar.currentMw, 0)} والرياح ${round(intelligence.wind.currentMw, 0)}. درجة الثقة بالمتجددة ${round(intelligence.confidenceScore, 0)}.`
          : `Renewable output is ${round(intelligence.totalCurrentMw, 0)} MW against ${round(intelligence.totalCapacityMw, 0)} MW installed — ${round(intelligence.solar.currentMw, 0)} MW solar and ${round(intelligence.wind.currentMw, 0)} MW wind. The renewable confidence score is ${round(intelligence.confidenceScore, 0)}.`,
        facts: [
          { label: ar ? 'الشمسية' : 'Solar', value: `${round(intelligence.solar.currentMw, 0)} MW` },
          { label: ar ? 'الرياح' : 'Wind', value: `${round(intelligence.wind.currentMw, 0)} MW` },
          {
            label: ar ? 'التذبذب المحتمل' : 'Variability',
            value: `±${round(intelligence.solar.variabilityMw + intelligence.wind.variabilityMw, 0)} MW`,
          },
          {
            label: ar ? 'درجة الثقة' : 'Confidence',
            value: String(round(intelligence.confidenceScore, 0)),
          },
        ],
        links: [{ label: ar ? 'ذكاء المتجددة' : 'Renewable intelligence', href: '/renewables' }],
        basedOn: ar ? 'نموذج المتجددة' : 'Renewable model',
      }
    }

    case 'asset_detail': {
      const denied = requires(user, 'assets.read', locale)
      if (denied) return denied

      const snapshot = await getGridSnapshot()
      const target = snapshot.assets.find((asset) => asset.profile.code === entities.assetCode)

      if (!target) {
        return {
          intent,
          answer: ar
            ? `لم أجد أصلًا بالرمز ${entities.assetCode}.`
            : `I could not find an asset with code ${entities.assetCode}.`,
          facts: [],
          links: [{ label: ar ? 'الأصول' : 'Assets', href: '/assets' }],
          basedOn: ar ? 'سجل الأصول' : 'Asset registry',
        }
      }

      return {
        intent,
        answer: ar
          ? `${target.profile.code} في ${regionName(target.profile.regionCode, locale)}: التحميل ${pct(target.sample.loadPct)}، الحرارة ${round(target.sample.tempC, 0)} مئوية، الصحة ${round(target.sample.effectiveHealth, 0)}، درجة الخطر ${pct(target.risk.score)}.`
          : `${target.profile.code} in ${regionName(target.profile.regionCode, locale)}: ${pct(target.sample.loadPct)} loading, ${round(target.sample.tempC, 0)} °C, health ${round(target.sample.effectiveHealth, 0)}, risk ${pct(target.risk.score)}.`,
        facts: [
          { label: ar ? 'التحميل' : 'Loading', value: pct(target.sample.loadPct) },
          {
            label: ar ? 'الحرارة' : 'Temperature',
            value: `${round(target.sample.tempC, 0)} °C`,
            tone: target.sample.tempC >= target.profile.ratedTempC ? 'critical' : 'normal',
          },
          { label: ar ? 'الصحة' : 'Health', value: String(round(target.sample.effectiveHealth, 0)) },
          {
            label: ar ? 'الخطر' : 'Risk',
            value: pct(target.risk.score),
            tone: target.risk.score >= 75 ? 'critical' : target.risk.score >= 55 ? 'warning' : 'normal',
          },
        ],
        links: [
          {
            label: ar ? 'فتح الأصل' : 'Open asset',
            href: `/assets/${encodeURIComponent(target.profile.code)}`,
          },
        ],
        basedOn: ar ? 'لقطة الشبكة الحية' : 'Live grid snapshot',
      }
    }

    case 'grid_status': {
      const denied = requires(user, 'grid.read', locale)
      if (denied) return denied

      const snapshot = await getGridSnapshot()
      return {
        intent,
        answer: ar
          ? `الحمل الوطني ${round(snapshot.totalLoadMw, 0)} ميجاواط من قدرة ${round(snapshot.totalCapacityMw, 0)} ميجاواط، بهامش احتياطي ${pct(snapshot.reserveMarginPct)}. مؤشر الاستقرار ${round(snapshot.stabilityIndex, 1)} والتردد ${snapshot.frequencyHz} هرتز. ${snapshot.criticalAssets.length} أصلًا يحتاج متابعة.`
          : `National load is ${round(snapshot.totalLoadMw, 0)} MW against ${round(snapshot.totalCapacityMw, 0)} MW of capacity, a ${pct(snapshot.reserveMarginPct)} reserve margin. Stability index ${round(snapshot.stabilityIndex, 1)}, frequency ${snapshot.frequencyHz} Hz. ${snapshot.criticalAssets.length} asset(s) need attention.`,
        facts: [
          { label: ar ? 'الحمل' : 'Load', value: `${round(snapshot.totalLoadMw, 0)} MW` },
          { label: ar ? 'الاستقرار' : 'Stability', value: String(round(snapshot.stabilityIndex, 1)) },
          { label: ar ? 'التردد' : 'Frequency', value: `${snapshot.frequencyHz} Hz` },
          { label: ar ? 'المتجددة' : 'Renewables', value: pct(snapshot.renewableSharePct) },
        ],
        links: [
          { label: ar ? 'مركز القيادة' : 'Command Center', href: '/command-center' },
          { label: ar ? 'حالة الشبكة' : 'Grid status', href: '/grid' },
        ],
        basedOn: ar ? 'لقطة الشبكة الحية' : 'Live grid snapshot',
      }
    }

    case 'riskiest_asset': {
      const denied = requires(user, 'grid.read', locale)
      if (denied) return denied

      const focusCode = entities.assetCode ?? (await pickFocusAsset())
      const intel = focusCode ? await analyseAsset(focusCode) : null
      if (!intel) break

      const cause = intel.rootCause.primary
      return {
        intent,
        answer: ar
          ? `أخطر أصل الآن هو ${intel.assetCode} بخطر موحّد ${pct(intel.orchestration.unifiedRisk)}${
              intel.prediction.etaMinutes === null
                ? ' دون تجاوز متوقع لأي حد داخل الأفق'
                : `، مع تقدير تجاوز حد خلال ${intel.prediction.etaMinutes} دقيقة`
            }. ${cause ? `والتفسير الأرجح: ${cause.labelAr}.` : ''}`
          : `${intel.assetCode} carries the highest exposure right now at a unified risk of ${pct(intel.orchestration.unifiedRisk)}${
              intel.prediction.etaMinutes === null
                ? ' with no limit breach predicted inside the horizon'
                : `, with a limit breach estimated in ${intel.prediction.etaMinutes} minutes`
            }. ${cause ? `The strongest explanation is ${cause.label.toLowerCase()}.` : ''}`,
        facts: [
          {
            label: ar ? 'التحميل' : 'Loading',
            value: pct(Math.abs(intel.focus.sample.loadPct)),
            tone: Math.abs(intel.focus.sample.loadPct) > 95 ? 'critical' : 'warning',
          },
          {
            label: ar ? 'الحرارة' : 'Temperature',
            value: `${round(intel.focus.sample.tempC, 1)} °C`,
          },
          {
            label: ar ? 'ثقة القرار' : 'Decision confidence',
            value: pct(intel.orchestration.confidence.overall),
          },
          {
            label: ar ? 'المشتركون' : 'Customers',
            value: intel.focus.profile.customersServed.toLocaleString('en-US'),
          },
        ],
        links: [
          { label: ar ? 'غرفة عمليات الذكاء' : 'AI Operations Room', href: `/ai-operations?asset=${intel.assetCode}` },
          { label: ar ? 'جواز الأصل' : 'Asset passport', href: `/assets/${intel.assetCode}` },
        ],
        basedOn: ar ? 'المنسّق ووكلاء التحليل' : 'Orchestrator and the agent panel',
      }
    }

    case 'root_cause': {
      const denied = requires(user, 'predictions.read', locale)
      if (denied) return denied

      const focusCode = entities.assetCode ?? (await pickFocusAsset())
      const intel = focusCode ? await analyseAsset(focusCode) : null
      if (!intel || !intel.rootCause.primary) break

      const cause = intel.rootCause.primary
      return {
        intent,
        answer: ar ? intel.rootCause.summaryAr : intel.rootCause.summary,
        facts: [
          { label: ar ? 'السبب الأرجح' : 'Most likely cause', value: ar ? cause.labelAr : cause.label },
          { label: ar ? 'الدليل' : 'Evidence', value: ar ? cause.evidenceAr : cause.evidence },
          { label: ar ? 'الثقة' : 'Confidence', value: pct(intel.rootCause.confidence) },
          ...intel.rootCause.alternatives.slice(0, 2).map((entry) => ({
            label: ar ? 'سبب مساهم' : 'Contributing cause',
            value: ar ? entry.labelAr : entry.label,
          })),
        ],
        links: [
          { label: ar ? 'السبب الجذري' : 'Root cause', href: `/ai-operations?asset=${intel.assetCode}` },
        ],
        basedOn: ar ? 'محرك السبب الجذري' : 'Root Cause engine',
      }
    }

    case 'cascade_impact': {
      const denied = requires(user, 'simulations.read', locale)
      if (denied) return denied

      const focusCode = entities.assetCode ?? (await pickFocusAsset())
      const intel = focusCode ? await analyseAsset(focusCode) : null
      if (!intel) break

      const propagating = intel.cascade.steps.filter((step) => step.outcome === 'failed' && step.depth > 0)
      return {
        intent,
        answer:
          propagating.length === 0
            ? ar
              ? `عطل ${intel.assetCode} يبقى محصورًا: الوحدات المجاورة تستوعب التحويل دون تجاوز حدودها.`
              : `A failure on ${intel.assetCode} stays contained — the neighbouring units absorb the transfer without exceeding their own limits.`
            : ar
              ? `عطل ${intel.assetCode} ينتشر إلى ${propagating.length} أصول إضافية خلال ${propagating.at(-1)?.offsetMin ?? 0} دقيقة، ويطال ${intel.cascade.affectedCustomers.toLocaleString('en-US')} مشترك. أول أثر تبعي على ${propagating[0].assetCode} عند +${propagating[0].offsetMin} دقيقة.`
              : `A failure on ${intel.assetCode} propagates to ${propagating.length} further assets over ${propagating.at(-1)?.offsetMin ?? 0} minutes and reaches ${intel.cascade.affectedCustomers.toLocaleString('en-US')} customers. The first knock-on hits ${propagating[0].assetCode} at +${propagating[0].offsetMin} minutes.`,
        facts: intel.cascade.steps.slice(0, 5).map((step) => ({
          label: `+${step.offsetMin} ${ar ? 'دقيقة' : 'min'} · ${step.assetCode}`,
          value: `${round(step.loadPctAfter, 0)}% · ${pct(step.probability * 100)}`,
          tone: step.outcome === 'failed' ? 'critical' : 'warning',
        })),
        links: [{ label: ar ? 'عرض الدومينو' : 'Domino View', href: `/cascade?asset=${intel.assetCode}` }],
        basedOn: ar ? 'محرك الأعطال المتتالية على الرسم الشبكي' : 'Cascade engine over the grid graph',
      }
    }

    case 'minimum_action': {
      const denied = requires(user, 'counterfactual.run', locale)
      if (denied) return denied

      const focusCode = entities.assetCode ?? (await pickFocusAsset())
      if (!focusCode) break
      const target = entities.deltaPct ?? 12
      const outcome = await runCounterfactual({
        assetCode: focusCode,
        objective: 'risk_below',
        targetValue: target,
      })
      if (!outcome) break

      return {
        intent,
        answer: ar ? outcome.summaryAr : outcome.summary,
        facts: [
          ...outcome.result.doses.map((dose) => ({
            label: ar ? dose.labelAr : dose.label,
            value: `−${round(dose.contribution, 1)} ${ar ? 'نقطة' : 'pts'}`,
            tone: 'normal' as const,
          })),
          {
            label: ar ? 'الخطر' : 'Risk',
            value: `${pct(outcome.riskBefore)} → ${pct(outcome.riskAfter)}`,
            tone: outcome.result.achieved ? ('normal' as const) : ('warning' as const),
          },
        ],
        links: [
          { label: ar ? 'مستكشف البدائل' : 'Counterfactual Explorer', href: `/counterfactual?asset=${focusCode}` },
        ],
        basedOn: ar ? 'بحث أقل تدخل على التوأم الرقمي' : 'Minimum-intervention search on the digital twin',
      }
    }

    case 'compare_strategies': {
      const denied = requires(user, 'simulations.read', locale)
      if (denied) return denied

      const focusCode = entities.assetCode ?? (await pickFocusAsset())
      const intel = focusCode ? await analyseAsset(focusCode) : null
      if (!intel) break

      const ranked = intel.optimisation.strategies
      const best = intel.optimisation.best
      return {
        intent,
        answer: ar
          ? `قُيّمت ${ranked.length} استراتيجيات على ${intel.assetCode} بالهدف نفسه. ${best ? `الأفضل هي ${best.labelAr} بدرجة ${round(best.score, 1)}، وتنقل الخطر من ${pct(best.evaluation.riskBefore)} إلى ${pct(best.evaluation.riskAfter)}.` : 'لا توجد استراتيجية تتفوق على عدم التدخل.'}`
          : `${ranked.length} strategies were scored on ${intel.assetCode} against the same objective. ${best ? `${best.label} wins with a score of ${round(best.score, 1)}, taking risk from ${pct(best.evaluation.riskBefore)} to ${pct(best.evaluation.riskAfter)}.` : 'None beats leaving the asset alone.'}`,
        facts: ranked.slice(0, 4).map((strategy) => ({
          label: ar ? strategy.labelAr : strategy.label,
          value: `${pct(strategy.evaluation.riskAfter)} · ${round(strategy.score, 1)}`,
          tone: strategy.isRecommended ? ('normal' as const) : ('warning' as const),
        })),
        links: [
          { label: ar ? 'مختبر التعافي الذاتي' : 'Self-Healing Lab', href: `/self-healing?asset=${intel.assetCode}` },
        ],
        basedOn: ar ? 'محرك التحسين متعدد الأهداف' : 'Multi-objective optimisation engine',
      }
    }

    case 'worst_case': {
      const denied = requires(user, 'simulations.read', locale)
      if (denied) return denied

      const focusCode = entities.assetCode ?? (await pickFocusAsset())
      const intel = focusCode ? await analyseAsset(focusCode) : null
      if (!intel) break

      const branches = await futureBranches(intel)
      const worst = branches.find((branch) => branch.key === 'no_action') ?? branches[0]
      return {
        intent,
        answer: ar
          ? `أسوأ مسار على ${intel.assetCode} هو عدم التدخل: يبلغ الخطر ${pct(worst.risk)} عند الأفق، ويطال ${worst.assetsAffected} أصلًا و${worst.customersAffected.toLocaleString('en-US')} مشترك، بانقطاع محتمل ${worst.potentialDowntimeMin} دقيقة. والنطاق التقديري للخطر بين ${pct(intel.orchestration.uncertainty.bestCaseRisk)} و${pct(intel.orchestration.uncertainty.worstCaseRisk)}.`
          : `The worst branch on ${intel.assetCode} is taking no action: risk reaches ${pct(worst.risk)} at the horizon, ${worst.assetsAffected} assets and ${worst.customersAffected.toLocaleString('en-US')} customers are implicated, and potential downtime is ${worst.potentialDowntimeMin} minutes. The credible risk band runs from ${pct(intel.orchestration.uncertainty.bestCaseRisk)} to ${pct(intel.orchestration.uncertainty.worstCaseRisk)}.`,
        facts: branches.map((branch) => ({
          label: ar ? branch.labelAr : branch.label,
          value: `${pct(branch.risk)} · ${branch.assetsAffected} ${ar ? 'أصل' : 'assets'}`,
          tone: branch.key === 'no_action' ? ('critical' as const) : ('normal' as const),
        })),
        links: [{ label: ar ? 'مسارات المستقبل' : 'Future branches', href: `/cascade?asset=${intel.assetCode}` }],
        basedOn: ar ? 'إعادة تشغيل التوأم لكل مسار' : 'A full twin re-run per branch',
      }
    }

    case 'weakest_link': {
      const denied = requires(user, 'grid.read', locale)
      if (denied) return denied

      const analysis = await getWeakLinkAnalysis({ limit: 5 })
      const weakest = analysis.weakest
      if (!weakest) break

      return {
        intent,
        answer: ar
          ? `الحلقة الأضعف الآن هي ${weakest.code} — ${weakest.reasonAr}. درجة التعرض ${round(weakest.exposureScore, 0)} من ١٠٠، وصعوبة التعافي ${round(weakest.recoveryDifficulty, 0)}، ويعتمد عليها ${weakest.downstreamCustomers.toLocaleString('en-US')} مشترك.`
          : `${weakest.code} is the weakest link right now — ${weakest.reason}. Exposure scores ${round(weakest.exposureScore, 0)} of 100 with a recovery difficulty of ${round(weakest.recoveryDifficulty, 0)}, and ${weakest.downstreamCustomers.toLocaleString('en-US')} customers sit behind it.`,
        facts: analysis.ranked.slice(0, 5).map((entry) => ({
          label: entry.code,
          value: `${round(entry.exposureScore, 0)} · ${pct(entry.riskScore)}`,
          tone: entry.hasRedundancy ? ('warning' as const) : ('critical' as const),
        })),
        links: [{ label: ar ? 'رادار المخاطر' : 'Risk radar', href: '/risk-radar' }],
        basedOn: ar ? 'تقييم الأهمية عبر الأسطول' : 'Fleet-wide criticality scoring',
      }
    }

    case 'hunt_risks': {
      const denied = requires(user, 'riskhunter.read', locale)
      if (denied) return denied

      // Reads what the hunter has already found rather than starting a search: a deep
      // sweep is the most expensive request the platform accepts, and a question is not
      // consent to spend it.
      const hunts = await listHunts(3)
      const findings = hunts.flatMap((hunt) => hunt.findings)
      if (findings.length === 0) {
        return {
          intent,
          answer: ar
            ? 'لم يُشغَّل صائد المخاطر بعد، فلا توجد نتائج لعرضها. افتح صائد المخاطر واختر عمق البحث لبدء عملية.'
            : 'The risk hunter has not been run yet, so there is nothing to report. Open the Risk Hunter and choose a search depth to start one.',
          facts: [],
          links: [{ label: ar ? 'صائد المخاطر' : 'Risk Hunter', href: '/risk-hunter' }],
          basedOn: ar ? 'سجل عمليات الصيد' : 'The hunt record',
        }
      }

      const top = [...findings].sort((a, b) => b.noveltyScore - a.noveltyScore)[0]
      return {
        intent,
        answer: ar
          ? `أحدث ما وجده الصائد: ${top.narrativeAr} هذه نتيجة محاكاة من ${hunts[0].simulationsRun} عملية، ولم تُطبَّق على الشبكة.`
          : `The most novel finding on record: ${top.narrative} This is a simulated result from ${hunts[0].simulationsRun} runs; nothing has been applied to the grid.`,
        facts: findings.slice(0, 5).map((finding) => ({
          label: finding.assetCode,
          value: `${round(finding.noveltyScore, 0)} · ${pct(finding.probability)}`,
          tone: finding.severity >= 70 ? ('critical' as const) : ('warning' as const),
        })),
        links: [{ label: ar ? 'صائد المخاطر' : 'Risk Hunter', href: '/risk-hunter' }],
        basedOn: ar ? 'نتائج محاكاة — صائد المخاطر' : 'Simulated findings from the risk hunter',
      }
    }

    case 'prove_it': {
      const denied = requires(user, 'proof.read', locale)
      if (denied) return denied

      const proofs = await listProofs({ limit: 5, assetCode: entities.assetCode ?? undefined })
      const latest = proofs[0]
      if (!latest) {
        return {
          intent,
          answer: ar
            ? 'لا يوجد إثبات مجمّد بعد. افتح صفحة إثباتات القرارات واضغط «أثبت ذلك» لتجميد ما تعتمد عليه المنصة الآن.'
            : 'No proof has been frozen yet. Open Decision Proofs and press PROVE IT to freeze what the platform is relying on right now.',
          facts: [],
          links: [{ label: ar ? 'إثباتات القرارات' : 'Decision Proofs', href: '/proofs' }],
          basedOn: ar ? 'سجل الإثباتات' : 'The proof record',
        }
      }

      return {
        intent,
        answer: ar
          ? `أحدث إثبات لـ ${latest.assetCode} يسجل ${latest.frameCount} حدثًا وانخفاض الخطر من ${round(latest.riskBefore, 1)} إلى ${round(latest.riskAfter, 1)}. الأدلة ${latest.evidenceKind === 'observed' ? 'ملاحظة' : 'محاكاة'}.`
          : `The latest proof for ${latest.assetCode} records ${latest.frameCount} events and a risk move from ${round(latest.riskBefore, 1)} to ${round(latest.riskAfter, 1)}. The evidence is ${latest.evidenceKind}.`,
        facts: proofs.slice(0, 5).map((proof) => ({
          label: proof.assetCode,
          value: `${round(proof.riskBefore, 1)} → ${round(proof.riskAfter, 1)}`,
          tone: 'normal' as const,
        })),
        links: [{ label: ar ? 'إعادة التشغيل' : 'Replay', href: `/proofs/${latest.code}` }],
        basedOn: ar ? 'إثبات مجمّد' : 'A frozen decision proof',
      }
    }

    default:
      return fallback
  }

  return fallback
}
