// import axios from 'axios';

// // Configure API client for requirement processor
// const apiClient = axios.create({
//   baseURL: 'http://localhost:8001', // Direct to requirement processor
//   timeout: 30000,
//   headers: {
//     'Content-Type': 'application/json',
//   },
// });

// // Configure API client for Template-Manager service
// const templateApiClient = axios.create({
//   baseURL: 'http://localhost:8009', // Direct to template-manager
//   timeout: 30000,
//   headers: {
//     'Content-Type': 'application/json',
//   },
// });

// // ========================================
// // EXISTING REQUIREMENT PROCESSOR APIs
// // ========================================

// // Real AI-powered feature analysis
// export const analyzeCustomFeature = async (featureData) => {
//   try {
//     console.log('Sending to analyze-feature:', featureData);
    
//     const response = await apiClient.post('/api/v1/analyze-feature', {
//       description: featureData.description,
//       project_type: featureData.project_type,
//       feature_name: featureData.feature_name,
//       requirements: featureData.requirements
//     });
    
//     console.log('Analysis response:', response.data);
//     return response.data.analysis;
//   } catch (error) {
//     console.error('Feature analysis failed:', error);
//     throw new Error('AI analysis failed. Please try again.');
//   }
// };

// // ========================================
// // NEW TEMPLATE-MANAGER APIs
// // ========================================

// // Get all templates grouped by category (replaces PROJECT_CATEGORIES)
// export const getTemplatesByCategory = async () => {
//   try {
//     console.log('🏗️ Fetching templates by category from Template-Manager...');
    
//     const response = await templateApiClient.get('/api/templates');
    
//     if (response.data.success) {
//       console.log('✅ Templates fetched successfully:', response.data.data);
//       return response.data.data; // Returns grouped by category
//     } else {
//       throw new Error('Failed to fetch templates');
//     }
//   } catch (error) {
//     console.error('❌ Error fetching templates:', error);
//     throw new Error('Failed to load templates. Please try again.');
//   }
// };

// // Get specific template with features (replaces DEFAULT_FEATURES[type])
// export const getTemplateByType = async (templateType) => {
//   try {
//     console.log(`🎯 Fetching template features for type: ${templateType}`);
    
//     const response = await templateApiClient.get(`/api/templates/type/${templateType}`);
    
//     if (response.data.success) {
//       console.log('✅ Template features fetched:', response.data.data);
//       return response.data.data; // Returns template with features array
//     } else {
//       throw new Error(`Template type '${templateType}' not found`);
//     }
//   } catch (error) {
//     console.error('❌ Error fetching template features:', error);
//     throw new Error('Failed to load template features. Please try again.');
//   }
// };

// // Get features for a specific template ID
// export const getTemplateFeatures = async (templateId) => {
//   try {
//     console.log(`📋 Fetching features for template ID: ${templateId}`);
    
//     const response = await templateApiClient.get(`/api/templates/${templateId}/features`);
    
//     if (response.data.success) {
//       console.log('✅ Features fetched:', response.data.data);
//       return response.data.data; // Returns features array
//     } else {
//       throw new Error('Failed to fetch template features');
//     }
//   } catch (error) {
//     console.error('❌ Error fetching template features:', error);
//     throw new Error('Failed to load features. Please try again.');
//   }
// };

// // Add custom feature to template (for learning system)
// export const addCustomFeature = async (templateId, featureData) => {
//   try {
//     console.log(`🎨 Adding custom feature to template ${templateId}:`, featureData);
    
//     const response = await templateApiClient.post('/api/features', {
//       template_id: templateId,
//       feature_id: featureData.feature_id || `custom_${Date.now()}`,
//       name: featureData.name,
//       description: featureData.description,
//       feature_type: 'custom',
//       complexity: featureData.complexity,
//       created_by_user: true
//     });
    
//     if (response.data.success) {
//       console.log('✅ Custom feature added:', response.data.data);
//       return response.data.data;
//     } else {
//       throw new Error('Failed to add custom feature');
//     }
//   } catch (error) {
//     console.error('❌ Error adding custom feature:', error);
//     throw new Error('Failed to add custom feature. Please try again.');
//   }
// };

// // Track feature usage (for learning system)
// export const trackFeatureUsage = async (featureId, userSession, projectId) => {
//   try {
//     console.log(`📊 Tracking feature usage: ${featureId}`);
    
//     const response = await templateApiClient.put(`/api/features/${featureId}/usage`, {
//       user_session: userSession,
//       project_id: projectId
//     });
    
//     if (response.data.success) {
//       console.log('✅ Feature usage tracked');
//       return response.data.data;
//     }
//   } catch (error) {
//     console.error('❌ Error tracking feature usage:', error);
//     // Don't throw error for tracking - it's not critical
//   }
// };

// // Get template statistics
// export const getTemplateStats = async () => {
//   try {
//     console.log('📊 Fetching template statistics...');
    
//     const response = await templateApiClient.get('/api/templates/stats');
    
//     if (response.data.success) {
//       return response.data.data;
//     } else {
//       throw new Error('Failed to fetch template stats');
//     }
//   } catch (error) {
//     console.error('❌ Error fetching template stats:', error);
//     return null; // Non-critical, return null
//   }
// };

// // Get popular features across all templates
// export const getPopularFeatures = async (limit = 10) => {
//   try {
//     console.log(`🔥 Fetching top ${limit} popular features...`);
    
//     const response = await templateApiClient.get(`/api/features/popular?limit=${limit}`);
    
//     if (response.data.success) {
//       return response.data.data;
//     } else {
//       throw new Error('Failed to fetch popular features');
//     }
//   } catch (error) {
//     console.error('❌ Error fetching popular features:', error);
//     return []; // Non-critical, return empty array
//   }
// };

// // ========================================
// // UTILITY FUNCTIONS
// // ========================================

// // Transform Template-Manager data to match current component expectations
// export const transformTemplateData = (apiTemplates) => {
//   // Transform from Template-Manager format to PROJECT_CATEGORIES format
//   const transformed = {};
  
//   for (const [category, templates] of Object.entries(apiTemplates)) {
//     transformed[category] = templates.map(template => ({
//       type: template.type,
//       title: template.title,
//       description: template.description,
//       icon: template.icon,
//       gradient: template.gradient,
//       border: template.border,
//       text: template.text,
//       subtext: template.subtext,
//       features: template.features ? template.features.map(f => f.name) : []
//     }));
//   }
  
//   return transformed;
// };

// // Transform template features to match DEFAULT_FEATURES format
// export const transformFeatureData = (apiFeatures) => {
//   return apiFeatures.map(feature => ({
//     id: feature.feature_id,
//     name: feature.name,
//     description: feature.description,
//     type: feature.feature_type,
//     complexity: feature.complexity,
//     order: feature.display_order,
//     isDefault: feature.is_default,
//     usageCount: feature.usage_count,
//     rating: feature.user_rating
//   }));
// };

// // Generate session ID for tracking
// export const generateSessionId = () => {
//   return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
// };

// export default apiClient;




import axios from 'axios';

// Configure API client for requirement processor
const apiClient = axios.create({
  baseURL: 'https://backend.codenuk.com/api/requirements', // Via API gateway
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Configure API client for Template-Manager service
const templateApiClient = axios.create({
  baseURL: 'https://backend.codenuk.com/api/templates', // Via API gateway
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Configure API client for User-Auth service
const authApiClient = axios.create({
  baseURL: 'https://backend.codenuk.com/api/auth', // Via API gateway
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true, // Include cookies for session management
});

// ========================================
// AUTHENTICATION INTERCEPTORS
// ========================================

// Token management
let accessToken = localStorage.getItem('accessToken');
let refreshToken = localStorage.getItem('refreshToken');

// Add auth token to requests
const addAuthTokenInterceptor = (client) => {
  client.interceptors.request.use(
    (config) => {
      if (accessToken) {
        config.headers.Authorization = `Bearer ${accessToken}`;
      }
      return config;
    },
    (error) => Promise.reject(error)
  );
};

// Handle token refresh
const addTokenRefreshInterceptor = (client) => {
  client.interceptors.response.use(
    (response) => response,
    async (error) => {
      const originalRequest = error.config;

      if (error.response?.status === 401 && !originalRequest._retry) {
        originalRequest._retry = true;

        try {
          if (refreshToken) {
            const response = await authApiClient.post('/api/auth/refresh', {
              refreshToken: refreshToken
            });

            const { accessToken: newAccessToken, refreshToken: newRefreshToken } = response.data.data.tokens;
            
            setTokens(newAccessToken, newRefreshToken);
            
            // Retry original request with new token
            originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
            return client(originalRequest);
          }
        } catch (refreshError) {
          console.error('Token refresh failed:', refreshError);
          clearTokens();
          window.location.href = '/login';
          return Promise.reject(refreshError);
        }
      }

      return Promise.reject(error);
    }
  );
};

// Apply interceptors to auth client
addAuthTokenInterceptor(authApiClient);
addTokenRefreshInterceptor(authApiClient);

// Token management functions
export const setTokens = (newAccessToken, newRefreshToken) => {
  accessToken = newAccessToken;
  refreshToken = newRefreshToken;
  localStorage.setItem('accessToken', newAccessToken);
  localStorage.setItem('refreshToken', newRefreshToken);
};

export const clearTokens = () => {
  accessToken = null;
  refreshToken = null;
  localStorage.removeItem('accessToken');
  localStorage.removeItem('refreshToken');
};

export const getAccessToken = () => accessToken;
export const getRefreshToken = () => refreshToken;

// ========================================
// EXISTING REQUIREMENT PROCESSOR APIs
// ========================================

// Real AI-powered feature analysis
export const analyzeCustomFeature = async (featureData) => {
  try {
    console.log('Sending to analyze-feature:', featureData);
    
    const response = await apiClient.post('/api/v1/analyze-feature', {
      description: featureData.description,
      project_type: featureData.project_type,
      feature_name: featureData.feature_name,
      requirements: featureData.requirements
    });
    
    console.log('Analysis response:', response.data);
    return response.data.analysis;
  } catch (error) {
    console.error('Feature analysis failed:', error);
    throw new Error('AI analysis failed. Please try again.');
  }
};

// ========================================
// EXISTING TEMPLATE-MANAGER APIs
// ========================================

// Get all templates grouped by category (replaces PROJECT_CATEGORIES)
export const getTemplatesByCategory = async () => {
  try {
    console.log('🏗️ Fetching templates by category from Template-Manager...');
    
    const response = await templateApiClient.get('/api/templates');
    
    if (response.data.success) {
      console.log('✅ Templates fetched successfully:', response.data.data);
      return response.data.data; // Returns grouped by category
    } else {
      throw new Error('Failed to fetch templates');
    }
  } catch (error) {
    console.error('❌ Error fetching templates:', error);
    throw new Error('Failed to load templates. Please try again.');
  }
};

// Get specific template with features (replaces DEFAULT_FEATURES[type])
export const getTemplateByType = async (templateType) => {
  try {
    console.log(`🎯 Fetching template features for type: ${templateType}`);
    
    const response = await templateApiClient.get(`/api/templates/type/${templateType}`);
    
    if (response.data.success) {
      console.log('✅ Template features fetched:', response.data.data);
      return response.data.data; // Returns template with features array
    } else {
      throw new Error(`Template type '${templateType}' not found`);
    }
  } catch (error) {
    console.error('❌ Error fetching template features:', error);
    throw new Error('Failed to load template features. Please try again.');
  }
};

// Get features for a specific template ID
export const getTemplateFeatures = async (templateId) => {
  try {
    console.log(`📋 Fetching features for template ID: ${templateId}`);
    
    const response = await templateApiClient.get(`/api/templates/${templateId}/features`);
    
    if (response.data.success) {
      console.log('✅ Features fetched:', response.data.data);
      return response.data.data; // Returns features array
    } else {
      throw new Error('Failed to fetch template features');
    }
  } catch (error) {
    console.error('❌ Error fetching template features:', error);
    throw new Error('Failed to load features. Please try again.');
  }
};

// Add custom feature to template (for learning system)
export const addCustomFeature = async (templateId, featureData) => {
  try {
    console.log(`🎨 Adding custom feature to template ${templateId}:`, featureData);
    
    const response = await templateApiClient.post('/api/features', {
      template_id: templateId,
      feature_id: featureData.feature_id || `custom_${Date.now()}`,
      name: featureData.name,
      description: featureData.description,
      feature_type: 'custom',
      complexity: featureData.complexity,
      created_by_user: true
    });
    
    if (response.data.success) {
      console.log('✅ Custom feature added:', response.data.data);
      return response.data.data;
    } else {
      throw new Error('Failed to add custom feature');
    }
  } catch (error) {
    console.error('❌ Error adding custom feature:', error);
    throw new Error('Failed to add custom feature. Please try again.');
  }
};

// Track feature usage (for learning system)
export const trackFeatureUsage = async (featureId, userSession, projectId) => {
  try {
    console.log(`📊 Tracking feature usage: ${featureId}`);
    
    const response = await templateApiClient.put(`/api/features/${featureId}/usage`, {
      user_session: userSession,
      project_id: projectId
    });
    
    if (response.data.success) {
      console.log('✅ Feature usage tracked');
      return response.data.data;
    }
  } catch (error) {
    console.error('❌ Error tracking feature usage:', error);
    // Don't throw error for tracking - it's not critical
  }
};

// Get template statistics
export const getTemplateStats = async () => {
  try {
    console.log('📊 Fetching template statistics...');
    
    const response = await templateApiClient.get('/api/templates/stats');
    
    if (response.data.success) {
      return response.data.data;
    } else {
      throw new Error('Failed to fetch template stats');
    }
  } catch (error) {
    console.error('❌ Error fetching template stats:', error);
    return null; // Non-critical, return null
  }
};

// Get popular features across all templates
export const getPopularFeatures = async (limit = 10) => {
  try {
    console.log(`🔥 Fetching top ${limit} popular features...`);
    
    const response = await templateApiClient.get(`/api/features/popular?limit=${limit}`);
    
    if (response.data.success) {
      return response.data.data;
    } else {
      throw new Error('Failed to fetch popular features');
    }
  } catch (error) {
    console.error('❌ Error fetching popular features:', error);
    return []; // Non-critical, return empty array
  }
};

// ========================================
// NEW AUTHENTICATION APIs
// ========================================

// User Registration
export const register = async (userData) => {
  try {
    console.log('👤 Registering new user:', userData.email);
    
    const response = await authApiClient.post('/api/auth/register', userData);
    
    if (response.data.success) {
      console.log('✅ User registered successfully');
      return response.data.data;
    } else {
      throw new Error('Registration failed');
    }
  } catch (error) {
    console.error('❌ Registration failed:', error);
    throw new Error(error.response?.data?.message || 'Registration failed. Please try again.');
  }
};

// User Login
export const login = async (credentials) => {
  try {
    console.log('🔑 Logging in user:', credentials.email);
    
    const response = await authApiClient.post('/api/auth/login', credentials);
    
    if (response.data.success) {
      const { tokens, user, session } = response.data.data;
      
      // Store tokens
      setTokens(tokens.accessToken, tokens.refreshToken);
      
      console.log('✅ User logged in successfully');
      return { user, tokens, session };
    } else {
      throw new Error('Login failed');
    }
  } catch (error) {
    console.error('❌ Login failed:', error);
    throw new Error(error.response?.data?.message || 'Login failed. Please try again.');
  }
};

// User Logout
export const logout = async () => {
  try {
    console.log('🚪 Logging out user...');
    
    const response = await authApiClient.post('/api/auth/logout', {
      refreshToken: getRefreshToken()
    });
    
    // Clear tokens regardless of response
    clearTokens();
    
    console.log('✅ User logged out successfully');
    return response.data;
  } catch (error) {
    console.error('❌ Logout failed:', error);
    // Clear tokens even if logout fails
    clearTokens();
    throw new Error('Logout failed. Please try again.');
  }
};

// Get Current User Profile
export const getCurrentUser = async () => {
  try {
    console.log('👤 Fetching current user profile...');
    
    const response = await authApiClient.get('/api/auth/me');
    
    if (response.data.success) {
      console.log('✅ User profile fetched');
      return response.data.data;
    } else {
      throw new Error('Failed to fetch user profile');
    }
  } catch (error) {
    console.error('❌ Failed to fetch user profile:', error);
    throw new Error('Failed to load user profile. Please try again.');
  }
};

// Update User Profile
export const updateProfile = async (updates) => {
  try {
    console.log('📝 Updating user profile...');
    
    const response = await authApiClient.put('/api/auth/me', updates);
    
    if (response.data.success) {
      console.log('✅ Profile updated successfully');
      return response.data.data;
    } else {
      throw new Error('Failed to update profile');
    }
  } catch (error) {
    console.error('❌ Profile update failed:', error);
    throw new Error(error.response?.data?.message || 'Failed to update profile. Please try again.');
  }
};

// Change Password
export const changePassword = async (currentPassword, newPassword) => {
  try {
    console.log('🔒 Changing user password...');
    
    const response = await authApiClient.put('/api/auth/change-password', {
      currentPassword,
      newPassword
    });
    
    if (response.data.success) {
      console.log('✅ Password changed successfully');
      // Clear tokens to force re-login
      clearTokens();
      return response.data;
    } else {
      throw new Error('Failed to change password');
    }
  } catch (error) {
    console.error('❌ Password change failed:', error);
    throw new Error(error.response?.data?.message || 'Failed to change password. Please try again.');
  }
};

// Get User Feature Preferences
export const getUserFeaturePreferences = async (templateType) => {
  try {
    console.log(`📋 Fetching feature preferences for: ${templateType}`);
    
    const response = await authApiClient.get(`/api/auth/preferences/${templateType}`);
    
    if (response.data.success) {
      console.log('✅ Feature preferences fetched');
      return response.data.data;
    } else {
      throw new Error('Failed to fetch feature preferences');
    }
  } catch (error) {
    console.error('❌ Failed to fetch feature preferences:', error);
    return { templateType, preferences: [] }; // Return empty preferences on error
  }
};

// Set User Feature Preference
export const setUserFeaturePreference = async (templateType, featureId, preferenceType, customData = null) => {
  try {
    console.log(`🎯 Setting feature preference: ${preferenceType} ${featureId} in ${templateType}`);
    
    const response = await authApiClient.post('/api/auth/preferences', {
      templateType,
      featureId,
      preferenceType,
      customData
    });
    
    if (response.data.success) {
      console.log('✅ Feature preference set');
      return response.data.data;
    } else {
      throw new Error('Failed to set feature preference');
    }
  } catch (error) {
    console.error('❌ Failed to set feature preference:', error);
    throw new Error('Failed to save feature preference. Please try again.');
  }
};

// Get User Projects
export const getUserProjects = async (limit = 10) => {
  try {
    console.log('📁 Fetching user projects...');
    
    const response = await authApiClient.get(`/api/auth/projects?limit=${limit}`);
    
    if (response.data.success) {
      console.log('✅ User projects fetched');
      return response.data.data;
    } else {
      throw new Error('Failed to fetch user projects');
    }
  } catch (error) {
    console.error('❌ Failed to fetch user projects:', error);
    return { projects: [], count: 0 }; // Return empty projects on error
  }
};

// Save User Project
export const saveUserProject = async (projectData) => {
  try {
    console.log('💾 Saving user project:', projectData.project_name);
    
    const response = await authApiClient.post('/api/auth/projects', projectData);
    
    if (response.data.success) {
      console.log('✅ Project saved successfully');
      return response.data.data;
    } else {
      throw new Error('Failed to save project');
    }
  } catch (error) {
    console.error('❌ Failed to save project:', error);
    throw new Error('Failed to save project. Please try again.');
  }
};

// ========================================
// UTILITY FUNCTIONS
// ========================================

// Transform Template-Manager data to match current component expectations
export const transformTemplateData = (apiTemplates) => {
  // Transform from Template-Manager format to PROJECT_CATEGORIES format
  const transformed = {};
  
  for (const [category, templates] of Object.entries(apiTemplates)) {
    transformed[category] = templates.map(template => {
      // Extract feature names from the features array
      let featureNames = [];
      
      if (template.features && Array.isArray(template.features)) {
        featureNames = template.features.map(f => f.name);
      }
      
      console.log(`📋 Transformed features for ${template.title}:`, featureNames);
      
      return {
        type: template.type,
        title: template.title,
        description: template.description,
        icon: template.icon,
        gradient: template.gradient,
        border: template.border,
        text: template.text,
        subtext: template.subtext,
        features: featureNames
      };
    });
  }
  
  console.log('🔄 Final transformed templates:', transformed);
  return transformed;
};

// Transform template features to match DEFAULT_FEATURES format
export const transformFeatureData = (apiFeatures) => {
  return apiFeatures.map(feature => ({
    id: feature.feature_id,
    name: feature.name,
    description: feature.description,
    type: feature.feature_type,
    complexity: feature.complexity,
    order: feature.display_order,
    isDefault: feature.is_default,
    usageCount: feature.usage_count,
    rating: feature.user_rating,
    template_feature_id: feature.id // Store the database ID for tracking
  }));
};

// Generate session ID for tracking
export const generateSessionId = () => {
  return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
};

// Check if user is authenticated
export const isAuthenticated = () => {
  return !!getAccessToken();
};

export default apiClient;