// API Client for DSS MCP Server
const API_BASE = import.meta.env?.VITE_API_BASE || '/api';
const isDev = import.meta.env?.DEV;

class APIClient {
  constructor(baseUrl = API_BASE) {
    this.baseUrl = baseUrl;
    this.cache = new Map();
    this.cacheTimeout = 30000; // 30 seconds
  }

  async request(endpoint, options = {}) {
    const url = `${this.baseUrl}${endpoint}`;
    const config = {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      ...options
    };

    try {
      const response = await fetch(url, config);

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new APIError(
          errorData.message || `API Error: ${response.status} ${response.statusText}`,
          response.status,
          errorData
        );
      }

      return await response.json();
    } catch (error) {
      if (error instanceof APIError) throw error;
      if (isDev) console.error('[API]', error);
      throw new APIError(error.message || 'Network error', 0, null);
    }
  }

  async get(endpoint, useCache = false) {
    if (useCache) {
      const cached = this.cache.get(endpoint);
      if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
        return cached.data;
      }
    }

    const data = await this.request(endpoint, { method: 'GET' });

    if (useCache) {
      this.cache.set(endpoint, { data, timestamp: Date.now() });
    }

    return data;
  }

  async post(endpoint, data) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(data)
    });
  }

  clearCache() {
    this.cache.clear();
  }

  // DSS-specific methods
  async getHealth() {
    return this.get('/health', true);
  }

  async analyzeProject(path) {
    return this.post('/tools/dss_analyze_project', { path });
  }

  async extractTokens(path, sources = ['css', 'scss']) {
    return this.post('/tools/dss_extract_tokens', { path, sources });
  }

  async auditComponents(path) {
    return this.post('/tools/dss_audit_components', { path });
  }

  async findQuickWins(path) {
    return this.post('/tools/dss_find_quick_wins', { path });
  }

  async generateTheme(format, themeName = 'default') {
    return this.post('/tools/dss_generate_theme', { format, theme_name: themeName });
  }

  async syncFigma(fileKey) {
    return this.post('/tools/dss_sync_figma', { file_key: fileKey });
  }

  async setupStorybook(path, action = 'scan') {
    return this.post('/tools/dss_setup_storybook', { path, action });
  }

  async getStatus() {
    return this.get('/status', true);
  }

  async listThemes() {
    return this.get('/themes', true);
  }

  // Aggregated metrics for dashboards
  async getTeamMetrics(team) {
    try {
      const status = await this.getStatus();

      // Derive metrics from DSS status
      const baseMetrics = {
        tokens: status.token_count || 0,
        themes: status.themes?.length || 0,
        healthy: status.healthy || false
      };

      switch (team) {
        case 'ui':
          return {
            components: status.component_count || 0,
            tokens: baseMetrics.tokens,
            synced: status.figma_connected || false,
            stories: status.storybook_stories || 0
          };
        case 'ux':
          return {
            consistency: status.consistency_score || 0,
            violations: status.violation_count || 0,
            patterns: status.pattern_count || 0,
            tokens: baseMetrics.tokens
          };
        case 'qa':
          return {
            health: status.health_score || 0,
            quickWins: status.quick_win_count || 0,
            unused: status.unused_count || 0,
            coverage: status.coverage_percent || 0
          };
        default:
          return {};
      }
    } catch (error) {
      if (isDev) console.warn('[API] Failed to fetch metrics, using defaults');
      // Return sensible defaults on error
      return this.getDefaultMetrics(team);
    }
  }

  getDefaultMetrics(team) {
    const defaults = {
      ui: { components: 0, tokens: 0, synced: false, stories: 0 },
      ux: { consistency: 0, violations: 0, patterns: 0, tokens: 0 },
      qa: { health: 0, quickWins: 0, unused: 0, coverage: 0 }
    };
    return defaults[team] || {};
  }
}

// Custom API Error class
class APIError extends Error {
  constructor(message, status, data) {
    super(message);
    this.name = 'APIError';
    this.status = status;
    this.data = data;
  }
}

export const api = new APIClient();
export { APIError };
export default api;
