import axios from 'axios';
import * as cheerio from 'cheerio';

export interface Filament {
  brand: string;
  tip: string;
  finish: string;
  boja: string;
  refill: string;
  vakum: string;
  otvoreno: string;
  kolicina: string;
  cena: string;
}

const mockFilaments: Filament[] = [
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Mistletoe Green", refill: "", vakum: "vakuum x1", otvoreno: "otvorena x1", kolicina: "2", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Indigo Purple", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Black", refill: "", vakum: "", otvoreno: "2x otvorena", kolicina: "2", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Black", refill: "Da", vakum: "vakuum", otvoreno: "", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Jade White", refill: "", vakum: "vakuum", otvoreno: "", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Gray", refill: "", vakum: "vakuum", otvoreno: "", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Red", refill: "", vakum: "vakuum", otvoreno: "", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Hot Pink", refill: "", vakum: "vakuum", otvoreno: "", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Cocoa Brown", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "White", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Cotton Candy Cloud", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Sunflower Yellow", refill: "", vakum: "vakuum", otvoreno: "", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Yellow", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Magenta", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Beige", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Basic", boja: "Cyan", refill: "", vakum: "vakuum", otvoreno: "", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Matte", boja: "Scarlet Red", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Matte", boja: "Mandarin Orange", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Matte", boja: "Marine Blue", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Matte", boja: "Charcoal", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" },
  { brand: "BambuLab", tip: "PLA", finish: "Matte", boja: "Ivory White", refill: "", vakum: "", otvoreno: "otvorena", kolicina: "", cena: "" }
];

export async function fetchFromConfluence(env: any): Promise<Filament[]> {
  const confluenceUrl = env.CONFLUENCE_API_URL;
  const confluenceToken = env.CONFLUENCE_TOKEN;
  const pageId = env.CONFLUENCE_PAGE_ID;

  console.log('Confluence config:', { 
    url: confluenceUrl ? 'Set' : 'Missing',
    token: confluenceToken ? 'Set' : 'Missing',
    pageId: pageId || 'Missing'
  });

  if (!confluenceUrl || !confluenceToken || !pageId) {
    console.warn('Confluence configuration missing, using mock data');
    return mockFilaments;
  }

  try {
    console.log('Fetching from Confluence:', `${confluenceUrl}/wiki/rest/api/content/${pageId}`);
    
    // Create Basic auth token from email and API token
    const auth = Buffer.from(`dax@demirix.com:${confluenceToken}`).toString('base64');
    
    const response = await axios.get(
      `${confluenceUrl}/wiki/rest/api/content/${pageId}?expand=body.storage`,
      {
        headers: {
          'Authorization': `Basic ${auth}`,
          'Accept': 'application/json'
        }
      }
    );

    console.log('Response status:', response.status);
    const htmlContent = response.data.body?.storage?.value || '';
    
    if (!htmlContent) {
      console.error('No HTML content in response');
      throw new Error('No content found');
    }
    
    const filaments = parseConfluenceTable(htmlContent);
    
    // Always return parsed data, never fall back to mock
    console.log(`Returning ${filaments.length} filaments from Confluence`);
    return filaments;
  } catch (error) {
    console.error('Failed to fetch from Confluence:', error);
    if (axios.isAxiosError(error)) {
      console.error('Response:', error.response?.status, error.response?.data);
    }
    throw error; // Don't return mock data
  }
}

function parseConfluenceTable(html: string): Filament[] {
  const $ = cheerio.load(html);
  const filaments: Filament[] = [];
  
  console.log('HTML length:', html.length);
  console.log('Number of tables found:', $('table').length);
  
  // Find all tables and process each one
  $('table').each((tableIndex, table) => {
    let headers: string[] = [];
    
    // Get headers
    $(table).find('tr').first().find('th, td').each((_i, cell) => {
      headers.push($(cell).text().trim());
    });
    
    console.log(`Table ${tableIndex} headers:`, headers);
    
    // Skip if not our filament table (check for expected headers)
    if (!headers.includes('Boja') || !headers.includes('Brand')) {
      console.log(`Skipping table ${tableIndex} - missing required headers`);
      return;
    }
    
    // Process rows
    $(table).find('tr').slice(1).each((_rowIndex, row) => {
      const cells = $(row).find('td');
      if (cells.length >= headers.length) {
        const filament: any = {};
        
        cells.each((cellIndex, cell) => {
          const headerName = headers[cellIndex];
          const cellText = $(cell).text().trim();
          
          // Debug log for the problematic column
          if (cellIndex === 7) { // Količina should be the 8th column (index 7)
            console.log(`Column 7 - Header: "${headerName}", Value: "${cellText}"`);
          }
          
          // Map headers to our expected structure
          switch(headerName.toLowerCase()) {
            case 'brand':
              filament.brand = cellText;
              break;
            case 'tip':
              filament.tip = cellText;
              break;
            case 'finish':
              filament.finish = cellText;
              break;
            case 'boja':
              filament.boja = cellText;
              break;
            case 'refill':
              filament.refill = cellText;
              break;
            case 'vakum':
              filament.vakum = cellText;
              break;
            case 'otvoreno':
              filament.otvoreno = cellText;
              break;
            case 'količina':
            case 'kolicina':  // Handle possible typo
              filament.kolicina = cellText;
              break;
            case 'cena':
              filament.cena = cellText;
              break;
          }
        });
        
        // Only add if we have the required fields
        if (filament.brand && filament.boja) {
          filaments.push(filament as Filament);
        }
      }
    });
  });
  
  console.log(`Parsed ${filaments.length} filaments from Confluence`);
  return filaments; // Return whatever we found, don't fall back to mock
}