const API_URL = 'http://192.168.1.19:8080/api';
const API_TOKEN = 'c1cef980b7c73004f4ee880a42839313b863869f';






const fetch = require('node-fetch');

async function fetchLableStudioProject(projectid) {
    // 1. Trigger export
    const exportUrl = `${API_URL}/projects/${projectid}/export?exportType=JSON_MIN`;
    const headers = { Authorization: `Token ${API_TOKEN}` };
    let res = await fetch(exportUrl, { headers });
    if (!res.ok) {
        let errorText = await res.text().catch(() => '');
        console.error(`Failed to trigger export: ${res.status} ${res.statusText} - ${errorText}`);
        throw new Error(`Failed to trigger export: ${res.status} ${res.statusText}`);
    }
    let data = await res.json();
    // If data is an array, it's ready
    if (Array.isArray(data)) return data;
    // If not, poll for the export file
    let fileUrl = data.download_url || data.url || null;
    let tries = 0;
    while (!fileUrl && tries < 20) {
        await new Promise(r => setTimeout(r, 2000));
        res = await fetch(exportUrl, { headers });
        if (!res.ok) {
            let errorText = await res.text().catch(() => '');
            console.error(`Failed to poll export: ${res.status} ${res.statusText} - ${errorText}`);
            throw new Error(`Failed to poll export: ${res.status} ${res.statusText}`);
        }
        data = await res.json();
        fileUrl = data.download_url || data.url || null;
        tries++;
    }
    if (!fileUrl) throw new Error('Label Studio export did not become ready');
    // 2. Download the export file
    res = await fetch(fileUrl.startsWith('http') ? fileUrl : `${API_URL.replace('/api','')}${fileUrl}`, { headers });
    if (!res.ok) {
        let errorText = await res.text().catch(() => '');
        console.error(`Failed to download export: ${res.status} ${res.statusText} - ${errorText}`);
        throw new Error(`Failed to download export: ${res.status} ${res.statusText}`);
    }
    return await res.json();
}



async function fetchProjectIdsAndTitles() {
  try {
    const response = await fetch(`${API_URL}/projects/`, {
      headers: {
        'Authorization': `Token ${API_TOKEN}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      let errorText = await response.text().catch(() => '');
      console.error(`Failed to fetch projects: ${response.status} ${response.statusText} - ${errorText}`);
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();

    if (!data.results || !Array.isArray(data.results)) {
      throw new Error('API response does not contain results array');
    }

    // Extract id and title from each project
    const projects = data.results.map(project => ({
      id: project.id,
      title: project.title
    }));
    console.log(projects)
    return projects;

  } catch (error) {
    console.error('Failed to fetch projects:', error);
    return [];
  }
}

module.exports = { fetchLableStudioProject, fetchProjectIdsAndTitles };



//getLableStudioProject(20)
//fetchProjectIdsAndTitles()
