/**
 * @fileoverview Design System Detector
 *
 * Detects if a design system exists for the project or feature.
 * Checks multiple locations in priority order.
 *
 * @module design-system-detector
 */

import { existsSync, readFileSync } from 'fs';
import { join } from 'path';

/**
 * Detect design system for project or feature
 * @param {string} projectPath - Root path of the project
 * @param {string|null} featureName - Feature name (optional, checks feature-level if provided)
 * @returns {Object} { hasDesignSystem, path, isProjectLevel, isFeatureLevel, source }
 */
export function detectDesignSystem(projectPath, featureName = null) {
  const result = {
    hasDesignSystem: false,
    path: null,
    isProjectLevel: false,
    isFeatureLevel: false,
    source: null
  };

  // Priority 1: Feature-level design system (if feature specified)
  if (featureName) {
    const featureDesignSystemPath = join(
      projectPath,
      '.morph/project/outputs',
      featureName,
      'ui-design-system.md'
    );

    if (existsSync(featureDesignSystemPath)) {
      return {
        hasDesignSystem: true,
        path: featureDesignSystemPath,
        isProjectLevel: false,
        isFeatureLevel: true,
        source: 'feature-output'
      };
    }
  }

  // Priority 2: Project-level design system (markdown)
  const projectDesignSystemPath = join(projectPath, '.morph/project/design-system.md');
  if (existsSync(projectDesignSystemPath)) {
    return {
      hasDesignSystem: true,
      path: projectDesignSystemPath,
      isProjectLevel: true,
      isFeatureLevel: false,
      source: 'project-markdown'
    };
  }

  // Priority 3: Generated CSS design system
  const cssDesignSystemPath = join(projectPath, 'wwwroot/css/design-system.css');
  if (existsSync(cssDesignSystemPath)) {
    return {
      hasDesignSystem: true,
      path: cssDesignSystemPath,
      isProjectLevel: true,
      isFeatureLevel: false,
      source: 'generated-css'
    };
  }

  // Priority 4: Check common CSS locations for design system variables
  const commonCssLocations = [
    'wwwroot/css/site.css',
    'wwwroot/css/app.css',
    'styles/globals.css',
    'src/styles/globals.css'
  ];

  for (const cssPath of commonCssLocations) {
    const fullPath = join(projectPath, cssPath);
    if (existsSync(fullPath)) {
      // Check if file contains design system variables (CSS custom properties)
      try {
        const content = readFileSync(fullPath, 'utf8');

        // Look for CSS custom properties that indicate a design system
        // Match :root { ... --variable ... } (with newlines)
        const hasDesignTokens = /:root\s*\{[\s\S]*?--/.test(content);

        if (hasDesignTokens) {
          return {
            hasDesignSystem: true,
            path: fullPath,
            isProjectLevel: true,
            isFeatureLevel: false,
            source: 'existing-css-variables'
          };
        }
      } catch {
        // Continue checking other locations
      }
    }
  }

  // No design system found
  return result;
}

/**
 * Check if UI agents are active for a feature
 * @param {string} projectPath - Root path of the project
 * @param {string} featureName - Feature name
 * @returns {boolean} True if UI agents are active
 */
export function hasUIAgentsActive(projectPath, featureName) {
  try {
    const statePath = join(projectPath, '.morph/state.json');

    if (!existsSync(statePath)) {
      return false;
    }

    const state = JSON.parse(readFileSync(statePath, 'utf8'));

    // Handle both array and object format
    let feature;
    if (Array.isArray(state.features)) {
      feature = state.features.find(f => f.name === featureName);
    } else if (state.features && typeof state.features === 'object') {
      feature = state.features[featureName];
    }

    if (!feature || !feature.activeAgents) {
      return false;
    }

    // UI agents that require design system
    const uiAgents = [
      'blazor-builder',
      'ui-designer',
      'css-specialist',
      'nextjs-expert'
    ];

    return feature.activeAgents.some(agentId => uiAgents.includes(agentId));
  } catch {
    return false;
  }
}

/**
 * Get recommended design system locations based on project type
 * @param {string} projectPath - Root path of the project
 * @returns {Object} { markdown, css, description }
 */
export function getRecommendedLocations(projectPath) {
  try {
    const configPath = join(projectPath, '.morph/config/config.json');

    let projectType = 'unknown';
    if (existsSync(configPath)) {
      const config = JSON.parse(readFileSync(configPath, 'utf8'));
      projectType = config.project?.type || 'unknown';
    }

    // Default locations (Blazor)
    const locations = {
      markdown: '.morph/project/design-system.md',
      css: 'wwwroot/css/design-system.css',
      description: 'Project-level design system (shared across features)'
    };

    // Adjust based on project type
    if (projectType === 'nextjs' || projectType.includes('nextjs')) {
      locations.css = 'styles/design-system.css';
    }

    return locations;
  } catch {
    return {
      markdown: '.morph/project/design-system.md',
      css: 'wwwroot/css/design-system.css',
      description: 'Project-level design system (shared across features)'
    };
  }
}
