// src/utils/aiUtils.ts
import { isToolHosted, createToolSlug } from './toolHelpers.js';

export interface ModeConfig {
  placeholder: string;
  description: string;
  submitText: string;
  loadingText: string;
}

export function getModeConfig(): Record<string, ModeConfig> {
  return {
    workflow: {
      placeholder: "Beschreiben Sie Ihr forensisches Szenario... z.B. 'Verdacht auf Ransomware-Angriff auf Windows-Domänencontroller'",
      description: "Beschreiben Sie Ihre Untersuchungssituation und erhalten Empfehlungen für alle Phasen der Untersuchung.",
      submitText: "Empfehlungen generieren",
      loadingText: "Analysiere Szenario und generiere Empfehlungen..."
    },
    tool: {
      placeholder: "Beschreiben Sie Ihr Problem... z.B. 'Analyse von Android-Backups mit WhatsApp-Nachrichten'",
      description: "Beschreiben Sie Ihre Untersuchungssituation und erhalten Empfehlungen für eine spezifische Aufgabenstellung.",
      submitText: "Empfehlungen finden",
      loadingText: "Analysiere Anforderungen und suche passende Methode..."
    }
  };
}

export function generateShareURL(toolName: string, view: string, modal: string | null = null): string {
  const toolSlug = createToolSlug(toolName);
  const baseUrl = window.location.origin + window.location.pathname;
  const params = new URLSearchParams();
  params.set('tool', toolSlug);
  params.set('view', view);
  if (modal) {
    params.set('modal', modal);
  }
  return `${baseUrl}?${params.toString()}`;
}

export function getErrorMessage(error: Error): string {
  const errorMap = {
    '429': 'Zu viele Anfragen. Bitte warten Sie einen Moment.',
    '401': 'Authentifizierung erforderlich. Bitte melden Sie sich an.',
    '503': 'KI-Service vorübergehend nicht verfügbar.'
  };
  
  for (const [code, message] of Object.entries(errorMap)) {
    if (error.message.includes(code)) return message;
  }
  
  return `Fehler: ${error.message}`;
}

export function renderToolBadges(tool: any): string {
  const isMethod = tool.type === 'method';
  const hasValidProjectUrl = isToolHosted(tool);
  
  let badges = '';
  if (isMethod) {
    badges += '<span class="badge" style="background-color: var(--color-method); color: white;">Methode</span>';
  } else if (hasValidProjectUrl) {
    badges += '<span class="badge badge-primary">CC24-Server</span>';
  } else if (tool.license !== 'Proprietary') {
    badges += '<span class="badge badge-success">Open Source</span>';
  }
  
  if (tool.knowledgebase === true) {
    badges += '<span class="badge badge-error">📖</span>';
  }
  
  return badges;
}

export function getToolClass(tool: any, context: string = 'card'): string {
  const isMethod = tool.type === 'method';
  const hasValidProjectUrl = isToolHosted(tool);
  
  if (context === 'recommendation') {
    if (isMethod) return 'method';
    if (hasValidProjectUrl) return 'hosted';
    if (tool.license !== 'Proprietary') return 'oss';
    return '';
  } else {
    if (isMethod) return 'card-method';
    if (hasValidProjectUrl) return 'card-hosted';
    if (tool.license !== 'Proprietary') return 'card-oss';
    return '';
  }
}

export function getSuitabilityText(score: string): string {
  const texts = {
    high: 'GUT GEEIGNET',
    medium: 'GEEIGNET', 
    low: 'VIELLEICHT GEEIGNET'
  };
  return texts[score] || 'GEEIGNET';
}

export function truncateText(text: string, maxLength: number): string {
  if (!text || text.length <= maxLength) return text;
  return text.slice(0, maxLength) + '...';
}

export function sanitizeText(text: string): string {
  if (typeof text !== 'string') return '';
  
  return text
    .replace(/^#{1,6}\s+/gm, '')
    .replace(/^\s*[-*+]\s+/gm, '')
    .replace(/^\s*\d+\.\s+/gm, '')
    .replace(/\*\*(.+?)\*\*/g, '$1')
    .replace(/\*(.+?)\*/g, '$1')
    .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
    .replace(/```[\s\S]*?```/g, '[CODE BLOCK]')
    .replace(/`([^`]+)`/g, '$1')
    .replace(/<[^>]+>/g, '')
    .replace(/\n\s*\n\s*\n/g, '\n\n')
    .trim();
}

export function escapeHtml(text: string): string {
  if (typeof text !== 'string') return String(text);
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

export function renderConfidenceTooltip(confidence: any): string {
  if (!confidence || typeof confidence.overall !== 'number') return '';
  
  const confidenceColor = getConfidenceColor(confidence.overall);
  
  return `
    <span class="confidence-tooltip-trigger" 
          style="display: inline-flex; align-items: center; gap: 0.125rem; cursor: help; margin-left: 0.25rem; position: relative;"
          onmouseenter="this.querySelector('.confidence-tooltip').style.display = 'block'"
          onmouseleave="this.querySelector('.confidence-tooltip').style.display = 'none'"
          onclick="event.stopPropagation();">
      <div style="width: 6px; height: 6px; border-radius: 50%; background-color: ${confidenceColor}; flex-shrink: 0;"></div>
      <span style="font-size: 0.625rem; color: white; font-weight: 600; text-shadow: 0 1px 2px rgba(0,0,0,0.5);">${confidence.overall}%</span>
      
      <div class="confidence-tooltip" 
           style="display: none; position: absolute; top: 100%; right: 0; z-index: 1001; background: var(--color-bg); border: 1px solid var(--color-border); border-radius: 0.5rem; padding: 1rem; min-width: 320px; max-width: 400px; box-shadow: var(--shadow-lg); font-size: 0.75rem; color: var(--color-text); margin-top: 0.5rem;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem;">
          <strong style="font-size: 0.875rem; color: var(--color-primary);">KI-Vertrauenswertung</strong>
          <span style="background-color: ${confidenceColor}; color: white; font-weight: 600; padding: 0.125rem 0.375rem; border-radius: 0.25rem; font-size: 0.625rem;">${confidence.overall}%</span>
        </div>
        
        <div style="display: grid; grid-template-columns: 1fr; gap: 0.625rem; margin-bottom: 0.75rem;">
          <div style="background: var(--color-bg-secondary); padding: 0.5rem; border-radius: 0.375rem; border-left: 3px solid var(--color-accent);">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.25rem;">
              <span style="font-weight: 600; font-size: 0.6875rem; color: var(--color-text);">🔍 Semantische Relevanz</span>
              <strong style="color: var(--color-accent);">${confidence.semanticRelevance}%</strong>
            </div>
            <div style="font-size: 0.625rem; color: var(--color-text-secondary); line-height: 1.3;">
              Wie gut die Tool-Beschreibung semantisch zu Ihrer Anfrage passt
            </div>
          </div>
          
          <div style="background: var(--color-bg-secondary); padding: 0.5rem; border-radius: 0.375rem; border-left: 3px solid var(--color-primary);">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.25rem;">
              <span style="font-weight: 600; font-size: 0.6875rem; color: var(--color-text);">🎯 Aufgaben-Eignung</span>
              <strong style="color: var(--color-primary);">${confidence.taskSuitability}%</strong>
            </div>
            <div style="font-size: 0.625rem; color: var(--color-text-secondary); line-height: 1.3;">
              KI-bewertete Eignung für Ihre spezifische Aufgabenstellung
            </div>
          </div>
        </div>
        
        <div style="margin-top: 0.75rem; padding-top: 0.75rem; border-top: 1px solid var(--color-border); font-size: 0.625rem; color: var(--color-text-secondary); text-align: center;">
          Forensisch fundierte KI-Analyse
        </div>
      </div>
    </span>
  `;
}

function getConfidenceColor(confidence: number): string {
  if (confidence >= 80) return 'var(--color-accent)';
  if (confidence >= 60) return 'var(--color-warning)';
  return 'var(--color-error)';
}