/**
 * UI Feature Detector
 *
 * Analyzes spec.md to detect UI needs automatically.
 * Auto-triggers FASE 1.5: UI/UX when entities + CRUD are detected.
 *
 * MORPH-SPEC 3.0
 */

/**
 * Detect UI needs from spec content
 * @param {string} specContent - Content of spec.md
 * @returns {Object} UI needs analysis
 */
export function detectUINeeds(specContent) {
  const entities = parseEntities(specContent);
  const crudOperations = detectCRUD(specContent);
  const uiKeywords = detectUIKeywords(specContent);

  const uiNeeds = [];

  // Auto-detect CRUD UI needs
  for (const entity of entities) {
    if (crudOperations.create) {
      uiNeeds.push({
        type: 'form',
        entity: entity.name,
        operation: 'create',
        fields: entity.properties,
        priority: 'high'
      });
    }

    if (crudOperations.read || crudOperations.list) {
      uiNeeds.push({
        type: 'list',
        entity: entity.name,
        fields: entity.properties.filter(p => p.displayInList !== false),
        features: detectListFeatures(specContent),
        priority: 'high'
      });
    }

    if (crudOperations.update) {
      uiNeeds.push({
        type: 'form',
        entity: entity.name,
        operation: 'edit',
        fields: entity.properties,
        priority: 'medium'
      });
    }

    if (crudOperations.delete) {
      uiNeeds.push({
        type: 'confirm-dialog',
        entity: entity.name,
        operation: 'delete',
        priority: 'medium'
      });
    }
  }

  // Detect special UI components from keywords
  if (uiKeywords.wizard) {
    uiNeeds.push({
      type: 'wizard',
      steps: extractWizardSteps(specContent),
      priority: 'high'
    });
  }

  if (uiKeywords.dashboard) {
    uiNeeds.push({
      type: 'dashboard',
      widgets: extractDashboardWidgets(specContent),
      priority: 'high'
    });
  }

  if (uiKeywords.upload) {
    uiNeeds.push({
      type: 'file-upload',
      maxSize: extractMaxFileSize(specContent),
      allowedTypes: extractAllowedFileTypes(specContent),
      priority: 'high'
    });
  }

  const shouldTriggerUIPhase = uiNeeds.length > 0 ||
                                 entities.length > 0 ||
                                 uiKeywords.hasUIKeywords;

  return {
    shouldTrigger: shouldTriggerUIPhase,
    entities,
    crudOperations,
    uiNeeds,
    keywords: uiKeywords,
    confidence: calculateConfidence(entities, crudOperations, uiKeywords)
  };
}

/**
 * Parse entities from spec
 */
function parseEntities(specContent) {
  const entities = [];

  // Match pseudo-code entity definitions
  const entityPattern = /(?:class|entity|table)\s+(\w+)\s*{([^}]+)}/gi;
  let match;

  while ((match = entityPattern.exec(specContent)) !== null) {
    const entityName = match[1];
    const body = match[2];

    const properties = parseProperties(body);

    entities.push({
      name: entityName,
      properties,
      hasId: properties.some(p => p.name.toLowerCase() === 'id'),
      hasTimestamps: properties.some(p =>
        p.name.toLowerCase().includes('createdat') ||
        p.name.toLowerCase().includes('updatedat')
      )
    });
  }

  return entities;
}

/**
 * Parse properties from entity body
 */
function parseProperties(body) {
  const properties = [];
  const lines = body.split('\n').map(l => l.trim()).filter(l => l);

  for (const line of lines) {
    // Match: Type PropertyName or PropertyName: Type
    const match = line.match(/(?:(\w+)\s+(\w+)|(\w+)\s*:\s*(\w+))/);
    if (!match) continue;

    const type = match[1] || match[4];
    const name = match[2] || match[3];

    if (!type || !name) continue;

    properties.push({
      name,
      type,
      isRequired: !line.includes('?') && !line.includes('optional'),
      isNullable: line.includes('?'),
      displayInList: !isInternalProperty(name),
      isEnum: type.endsWith('Status') || type.endsWith('Type') || type.endsWith('Kind')
    });
  }

  return properties;
}

/**
 * Check if property is internal (not for display)
 */
function isInternalProperty(name) {
  const internalNames = ['id', 'createdat', 'updatedat', 'deletedat', 'version', 'rowversion'];
  return internalNames.includes(name.toLowerCase());
}

/**
 * Detect CRUD operations from spec
 */
function detectCRUD(specContent) {
  const lower = specContent.toLowerCase();

  return {
    create: /\b(create|add|new|insert|register|upload)\b/i.test(lower),
    read: /\b(read|get|view|show|display|retrieve|fetch)\b/i.test(lower),
    update: /\b(update|edit|modify|change)\b/i.test(lower),
    delete: /\b(delete|remove|destroy)\b/i.test(lower),
    list: /\b(list|index|all|search|filter|query)\b/i.test(lower)
  };
}

/**
 * Detect UI-specific keywords
 */
function detectUIKeywords(specContent) {
  const lower = specContent.toLowerCase();

  return {
    wizard: /\b(wizard|step|multi-?step|flow)\b/i.test(lower),
    dashboard: /\b(dashboard|overview|summary|stats|metrics)\b/i.test(lower),
    chart: /\b(chart|graph|visualization|plot)\b/i.test(lower),
    upload: /\b(upload|file|photo|image|document|attachment)\b/i.test(lower),
    modal: /\b(modal|dialog|popup|overlay)\b/i.test(lower),
    form: /\b(form|input|field|validation)\b/i.test(lower),
    table: /\b(table|grid|list|datagrid)\b/i.test(lower),
    hasUIKeywords: /\b(wizard|dashboard|chart|upload|modal|form|table|ui|ux|screen|page|component)\b/i.test(lower)
  };
}

/**
 * Detect list features (pagination, filters, etc.)
 */
function detectListFeatures(specContent) {
  const lower = specContent.toLowerCase();

  return {
    pagination: /\b(paginat|page|per.?page|offset|limit)\b/i.test(lower),
    sorting: /\b(sort|order|asc|desc)\b/i.test(lower),
    filtering: /\b(filter|search|query|where)\b/i.test(lower),
    selection: /\b(select|check|multi.?select|bulk)\b/i.test(lower),
    actions: /\b(action|edit|delete|view|export)\b/i.test(lower)
  };
}

/**
 * Extract wizard steps from spec
 */
function extractWizardSteps(specContent) {
  const steps = [];
  const stepPattern = /step\s+(\d+):\s*([^\n]+)/gi;
  let match;

  while ((match = stepPattern.exec(specContent)) !== null) {
    steps.push({
      number: parseInt(match[1]),
      title: match[2].trim()
    });
  }

  return steps.length > 0 ? steps : [
    { number: 1, title: 'Information' },
    { number: 2, title: 'Confirmation' }
  ];
}

/**
 * Extract dashboard widgets from spec
 */
function extractDashboardWidgets(specContent) {
  const widgets = [];

  if (/\b(stat|metric|kpi|count)\b/i.test(specContent)) {
    widgets.push({ type: 'stat-card', count: 3 });
  }

  if (/\b(chart|graph|visualization)\b/i.test(specContent)) {
    widgets.push({ type: 'chart', chartType: 'line' });
  }

  if (/\b(table|grid|list|recent)\b/i.test(specContent)) {
    widgets.push({ type: 'data-table', showActions: true });
  }

  return widgets;
}

/**
 * Extract max file size from spec
 */
function extractMaxFileSize(specContent) {
  const match = specContent.match(/(\d+)\s*(mb|gb|kb)/i);
  if (!match) return '10MB';

  const size = parseInt(match[1]);
  const unit = match[2].toLowerCase();

  return `${size}${unit.toUpperCase()}`;
}

/**
 * Extract allowed file types from spec
 */
function extractAllowedFileTypes(specContent) {
  const match = specContent.match(/\.(jpg|jpeg|png|pdf|doc|docx|xls|xlsx|csv|txt|zip)(?:\s*,\s*\.|\s+)/gi);
  if (!match) return ['.jpg', '.jpeg', '.png'];

  return match.map(m => m.trim().replace(/\s*,\s*$/, ''));
}

/**
 * Calculate confidence score
 */
function calculateConfidence(entities, crudOperations, uiKeywords) {
  let score = 0;

  // Entities detected
  if (entities.length > 0) score += 30;
  if (entities.length > 2) score += 10;

  // CRUD operations
  const crudCount = Object.values(crudOperations).filter(v => v).length;
  score += crudCount * 10;

  // UI keywords
  if (uiKeywords.hasUIKeywords) score += 20;
  if (uiKeywords.wizard) score += 15;
  if (uiKeywords.dashboard) score += 15;

  return Math.min(100, score);
}

/**
 * Generate UI phase trigger message
 */
export function generateUITriggerMessage(analysis) {
  if (!analysis.shouldTrigger) {
    return null;
  }

  const { entities, crudOperations, uiNeeds, confidence } = analysis;

  const parts = [];

  parts.push(`🎨 **UI/UX Auto-Detection** (${confidence}% confidence)`);
  parts.push('');

  if (entities.length > 0) {
    parts.push(`**Entities Detected:** ${entities.map(e => e.name).join(', ')}`);
  }

  if (Object.values(crudOperations).some(v => v)) {
    const ops = Object.entries(crudOperations)
      .filter(([k, v]) => v)
      .map(([k]) => k.toUpperCase());
    parts.push(`**CRUD Operations:** ${ops.join(', ')}`);
  }

  if (uiNeeds.length > 0) {
    parts.push('');
    parts.push('**UI Needs Detected:**');
    uiNeeds.forEach((need, i) => {
      const icon = need.type === 'form' ? '📝' :
                   need.type === 'list' ? '📋' :
                   need.type === 'wizard' ? '🧙' :
                   need.type === 'dashboard' ? '📊' : '🔧';
      parts.push(`${i + 1}. ${icon} ${need.type.toUpperCase()}: ${need.entity || need.operation || 'Generic'}`);
    });
  }

  parts.push('');
  parts.push('**➡️ Auto-triggering FASE 1.5: UI/UX Design**');
  parts.push('Generating wireframes, component specs, and design system...');

  return parts.join('\n');
}
