'use strict';

const TRANSIENT_PROVIDER_ISSUE_MAX_AGE_MS = 6 * 60 * 60 * 1000;

function asTime(value) {
  const t = value ? Date.parse(value) : NaN;
  return Number.isFinite(t) ? t : 0;
}

function normalizedProviderIssue(alert) {
  if (!alert || typeof alert !== 'object') return null;
  const issue = alert.providerError || alert.provider_error || {};
  const type = String(issue.type || alert.type || '').toLowerCase();
  const service = String(alert.service || '').toLowerCase();
  const looksProvider = service === 'ai_provider' || type.startsWith('ai_provider') || !!alert.provider || !!issue.provider;
  if (!looksProvider) return null;
  return {
    id: alert.id || '',
    type: issue.type || alert.type || 'provider_error',
    severity: issue.severity || alert.severity || 'error',
    title: issue.title || alert.title || 'AI provider issue',
    message: issue.userMessage || issue.message || alert.message || 'Wall-E could not get a provider response.',
    provider: issue.provider || alert.provider || '',
    model: issue.model || alert.model || '',
    status: issue.status || alert.status || '',
    rawMessage: issue.rawMessage || issue.raw_message || alert.rawMessage || '',
    actionUrl: issue.actionUrl || issue.action_url || alert.action_url || '/setup.html',
    actionLabel: issue.actionLabel || issue.action_label || alert.action_label || 'Open Setup',
    created_at: alert.created_at || issue.createdAt || issue.created_at || '',
  };
}

function providerMatches(issue, activeProvider, activeModel) {
  if (!issue) return false;
  const provider = String(issue.provider || '').toLowerCase();
  const model = String(issue.model || '').toLowerCase();
  const ap = String(activeProvider || '').toLowerCase();
  const am = String(activeModel || '').toLowerCase();
  if (ap && provider && provider === ap) return true;
  if (am && model && model === am) return true;
  return !ap && !am;
}

function isStickyProviderIssue(issue) {
  const text = `${issue.type || ''} ${issue.title || ''} ${issue.message || ''}`.toLowerCase();
  return /auth|quota|billing|credit|insufficient|invalid|forbidden|unauthorized|permission/.test(text);
}

function isCurrentProviderIssue(issue, opts, nowMs) {
  if (!providerMatches(issue, opts.activeProvider, opts.activeModel)) return false;
  if (isStickyProviderIssue(issue)) return true;
  const created = asTime(issue.created_at);
  if (!created) return true;
  return nowMs - created <= (opts.transientProviderMaxAgeMs || TRANSIENT_PROVIDER_ISSUE_MAX_AGE_MS);
}

function skillNameFromAlert(alert) {
  if (!alert) return '';
  if (alert.skill) return String(alert.skill);
  const service = String(alert.service || '');
  if (service && service !== 'ai_provider' && service !== 'system') return service;
  const msg = String(alert.message || '');
  const quoted = msg.match(/Skill\s+"([^"]+)"/i);
  if (quoted) return quoted[1];
  const named = msg.match(/Skill\s+([A-Za-z0-9_.-]+)/i);
  return named ? named[1] : '';
}

function isDisabledSkillAlert(alert) {
  return !!alert && String(alert.type || '').toLowerCase() === 'skill_disabled';
}

function isIntegrationAlert(alert) {
  if (!alert || isDisabledSkillAlert(alert)) return false;
  const type = String(alert.type || '').toLowerCase();
  const action = String(alert.action || '').toLowerCase();
  const text = [alert.service, alert.message, alert.integration].filter(Boolean).join(' ').toLowerCase();
  if (action === 'gws_reauth' || action === 'repair_slack_owner') return true;
  if (type === 'auth_expired' || type === 'owner_identity_missing') return true;
  return /(slack|gws|google|gmail|calendar|drive|oauth)/.test(text)
    && /(auth|reauth|reconnect|expired|token|owner)/.test(text);
}

function publicAlert(alert) {
  return {
    id: alert.id || '',
    service: alert.service || '',
    type: alert.type || '',
    title: alert.title || '',
    message: alert.message || '',
    severity: alert.severity || '',
    action: alert.action || '',
    action_label: alert.action_label || '',
    action_url: alert.action_url || '',
    created_at: alert.created_at || '',
  };
}

function summarizeProviderIssue(issue, nowMs) {
  const created = asTime(issue.created_at);
  return {
    id: issue.id,
    type: issue.type,
    severity: issue.severity,
    title: issue.title,
    message: issue.message,
    provider: issue.provider,
    model: issue.model,
    status: issue.status,
    action_url: issue.actionUrl,
    action_label: issue.actionLabel,
    created_at: issue.created_at,
    age_ms: created ? Math.max(0, nowMs - created) : null,
  };
}

function buildServiceHealth(alerts, options = {}) {
  const list = Array.isArray(alerts) ? alerts.filter(Boolean) : [];
  const nowMs = options.nowMs || Date.now();
  const providerIssues = list
    .map(normalizedProviderIssue)
    .filter(Boolean)
    .sort((a, b) => asTime(b.created_at) - asTime(a.created_at));

  const currentIssue = providerIssues.find((issue) => isCurrentProviderIssue(issue, options, nowMs)) || null;
  const currentIssueId = currentIssue && currentIssue.id;
  const providerHistory = providerIssues
    .filter((issue) => issue.id !== currentIssueId)
    .map((issue) => summarizeProviderIssue(issue, nowMs));

  const disabledSkills = list.filter(isDisabledSkillAlert).map((alert) => ({
    ...publicAlert(alert),
    skill: skillNameFromAlert(alert),
  }));
  const integrationAlerts = list
    .filter((alert) => !normalizedProviderIssue(alert) && !isDisabledSkillAlert(alert) && isIntegrationAlert(alert))
    .map(publicAlert);
  const systemAlerts = list
    .filter((alert) => !normalizedProviderIssue(alert) && !isDisabledSkillAlert(alert) && !isIntegrationAlert(alert))
    .map(publicAlert);

  let level = 'ok';
  if (currentIssue) level = currentIssue.severity === 'warning' ? 'warning' : 'error';
  else if (integrationAlerts.length || disabledSkills.length || systemAlerts.some((a) => a.severity === 'error')) level = 'warning';
  else if (providerHistory.length || systemAlerts.length) level = 'info';

  const activeLabel = [options.activeProvider, options.activeModel].filter(Boolean).join(' / ');
  let title = 'Wall-E services healthy';
  let message = activeLabel ? `${activeLabel} has no current service blocker.` : 'No current service blocker.';
  if (currentIssue) {
    title = currentIssue.title || 'Current provider issue';
    message = currentIssue.message;
  } else if (integrationAlerts.length || disabledSkills.length) {
    title = 'Background services need review';
    const parts = [];
    if (disabledSkills.length) parts.push(`${disabledSkills.length} disabled skill${disabledSkills.length === 1 ? '' : 's'}`);
    if (integrationAlerts.length) parts.push(`${integrationAlerts.length} integration alert${integrationAlerts.length === 1 ? '' : 's'}`);
    message = parts.join(' and ') + '.';
  } else if (providerHistory.length || systemAlerts.length) {
    title = 'Older service history';
    message = 'No current blocker, but older provider or system alerts are available for review.';
  }

  return {
    level,
    title,
    message,
    active_provider: {
      provider: options.activeProvider || '',
      model: options.activeModel || '',
    },
    current_issue: currentIssue ? summarizeProviderIssue(currentIssue, nowMs) : null,
    disabled_skills: disabledSkills,
    integration_alerts: integrationAlerts,
    provider_history: providerHistory,
    system_alerts: systemAlerts,
    counts: {
      total: list.length,
      current: currentIssue ? 1 : 0,
      disabled_skills: disabledSkills.length,
      integration: integrationAlerts.length,
      provider_history: providerHistory.length,
      system: systemAlerts.length,
    },
    updated_at: new Date(nowMs).toISOString(),
  };
}

module.exports = {
  buildServiceHealth,
  normalizedProviderIssue,
  skillNameFromAlert,
  TRANSIENT_PROVIDER_ISSUE_MAX_AGE_MS,
};
