import axios from 'axios';
import type { OffsetOrder, OffsetOrderSource, Portfolio } from '../types';
import { logger } from '../utils/logger';

// Default portfolio for fallback
const DEFAULT_PORTFOLIO: Portfolio = {
  id: 2,
  name: "Community Tree Planting",
  description: "A curated selection of high-impact carbon removal projects focused on carbon sequestration through tree planting.",
  projects: [
    {
      id: "tree-1",
      name: "Community Tree Planting",
      description: "Carbon sequestration through community tree planting",
      shortDescription: "Tree planting projects",
      imageUrl: "https://images.unsplash.com/photo-1513836279014-a89f7a76ae86",
      pricePerTon: 284.63,
      location: "Global",
      type: "Nature Based",
      verificationStandard: "Gold Standard",
      impactMetrics: {
        co2Reduced: 5000
      }
    }
  ],
  pricePerTon: 284.63,
  currency: 'USD'
};

/**
 * Get portfolios from Wren API via server-side proxy
 * This keeps the Wren API token secure on the server
 */
export async function getPortfolios(): Promise<Portfolio[]> {
  const startTime = Date.now();
  console.log('🔵 [WREN API] ========================================');
  console.log('🔵 [WREN API] GET /portfolios - Request initiated');
  console.log('🔵 [WREN API] Timestamp:', new Date().toISOString());

  try {
    console.log('🔵 [WREN API] Making request to proxy: /api/wren/portfolios');

    const response = await axios.get('/api/wren/portfolios');
    const duration = Date.now() - startTime;

    console.log('✅ [WREN API] GET /portfolios - Success');
    console.log('✅ [WREN API] Status:', response.status);
    console.log('✅ [WREN API] Duration:', duration + 'ms');
    console.log('✅ [WREN API] Portfolios returned:', response.data?.portfolios?.length || 0);

    if (response.data?.portfolios?.length > 0) {
      console.log('✅ [WREN API] Portfolio IDs:', response.data.portfolios.map((p: any) => `#${p.id} (${p.name})`).join(', '));
    }
    console.log('🔵 [WREN API] ========================================');

    if (!response.data?.portfolios?.length) {
      console.warn('⚠️  [WREN API] No portfolios in response, using fallback');
      logger.warn('[wrenClient] No portfolios returned from API, using fallback');
      return [DEFAULT_PORTFOLIO];
    }

    return response.data.portfolios.map((portfolio: any) => {
      let pricePerTon = 18; // Default price based on the Wren Climate Fund average

      // The API returns cost_per_ton in snake_case
      if (portfolio.cost_per_ton !== undefined && portfolio.cost_per_ton !== null) {
        pricePerTon = typeof portfolio.cost_per_ton === 'number' ? portfolio.cost_per_ton : parseFloat(portfolio.cost_per_ton) || 18;
      } else if (portfolio.costPerTon !== undefined && portfolio.costPerTon !== null) {
        pricePerTon = typeof portfolio.costPerTon === 'number' ? portfolio.costPerTon : parseFloat(portfolio.costPerTon) || 18;
      } else if (portfolio.pricePerTon !== undefined && portfolio.pricePerTon !== null) {
        pricePerTon = typeof portfolio.pricePerTon === 'number' ? portfolio.pricePerTon : parseFloat(portfolio.pricePerTon) || 18;
      }

      // Convert from snake_case to camelCase for projects
      const projects = portfolio.projects?.map((project: any) => {
        const projectPricePerTon = project.cost_per_ton !== undefined && project.cost_per_ton !== null
          ? (typeof project.cost_per_ton === 'number' ? project.cost_per_ton : parseFloat(project.cost_per_ton))
          : pricePerTon;

        const projectPercentage = project.percentage !== undefined && project.percentage !== null
          ? (typeof project.percentage === 'number' ? project.percentage : parseFloat(project.percentage))
          : undefined;

        return {
          id: project.id || `project-${Math.random().toString(36).substring(2, 9)}`,
          name: project.name,
          description: project.description || '',
          shortDescription: project.short_description || project.description || '',
          imageUrl: project.image_url,
          pricePerTon: projectPricePerTon,
          percentage: projectPercentage,
          certificationStatus: project.certification_status,
          location: '',
          type: '',
          verificationStandard: '',
          impactMetrics: {
            co2Reduced: 0
          }
        };
      }) || [];

      return {
        id: portfolio.id,
        name: portfolio.name,
        description: portfolio.description || '',
        projects: projects,
        pricePerTon,
        currency: 'USD'
      };
    });
  } catch (error) {
    const duration = Date.now() - startTime;
    console.error('❌ [WREN API] GET /portfolios - Failed');
    console.error('❌ [WREN API] Duration:', duration + 'ms');

    if (axios.isAxiosError(error)) {
      console.error('❌ [WREN API] Status:', error.response?.status || 'No response');
      console.error('❌ [WREN API] Error Data:', JSON.stringify(error.response?.data, null, 2));
    } else {
      console.error('❌ [WREN API] Error:', error instanceof Error ? error.message : String(error));
    }
    console.log('🔵 [WREN API] ========================================');

    logger.warn('[wrenClient] Failed to fetch portfolios from API, using fallback');
    return [DEFAULT_PORTFOLIO];
  }
}

/**
 * Create offset order with Wren API via server-side proxy
 * This keeps the Wren API token secure on the server
 */
export async function createOffsetOrder(
  portfolioId: number,
  tons: number,
  dryRun: boolean = false,
  source?: OffsetOrderSource,
  note?: string
): Promise<OffsetOrder> {
  const startTime = Date.now();
  console.log('🔵 [WREN API] ========================================');
  console.log('🔵 [WREN API] POST /offset-orders - Request initiated');
  console.log('🔵 [WREN API] Timestamp:', new Date().toISOString());
  console.log('🔵 [WREN API] Parameters:', JSON.stringify({ portfolioId, tons, dryRun, source, note }, null, 2));

  try {
    console.log('🔵 [WREN API] Making request to proxy: /api/wren/offset-orders');
    logger.log(`[wrenClient] Creating offset order via proxy: portfolio=${portfolioId}, tons=${tons}, dryRun=${dryRun}`);

    const response = await axios.post('/api/wren/offset-orders', {
      tons,
      portfolioId,
      dryRun,
      source,
      note
    });

    const duration = Date.now() - startTime;

    console.log('✅ [WREN API] POST /offset-orders - Success');
    console.log('✅ [WREN API] Status:', response.status);
    console.log('✅ [WREN API] Duration:', duration + 'ms');
    console.log('✅ [WREN API] Order ID:', response.data.id);
    console.log('✅ [WREN API] Amount Charged:', response.data.amount_paid_by_customer);
    console.log('🔵 [WREN API] ========================================');

    logger.log(`[wrenClient] Order created successfully: ${response.data.id}`);

    return {
      id: response.data.id,
      amountCharged: response.data.amount_paid_by_customer,
      currency: (response.data.currency?.toUpperCase() || 'USD') as 'USD' | 'EUR' | 'GBP' | 'CHF',
      tons: response.data.tons,
      portfolio: response.data.portfolio,
      status: 'completed',
      createdAt: new Date().toISOString(),
      dryRun,
      source,
      note
    };
  } catch (error) {
    const duration = Date.now() - startTime;
    console.error('❌ [WREN API] POST /offset-orders - Failed');
    console.error('❌ [WREN API] Duration:', duration + 'ms');

    if (axios.isAxiosError(error)) {
      console.error('❌ [WREN API] Status:', error.response?.status || 'No response');
      console.error('❌ [WREN API] Error Data:', JSON.stringify(error.response?.data, null, 2));
      console.error('❌ [WREN API] Request URL:', error.config?.url);
    } else {
      console.error('❌ [WREN API] Error:', error instanceof Error ? error.message : String(error));
    }
    console.log('🔵 [WREN API] ========================================');

    logger.error('[wrenClient] Failed to create offset order');
    throw new Error('Failed to create carbon offset order. Please try again or contact support.');
  }
}
