import type { Product, TargetIndustry, Keyword, CompetitorCandidate, Analysis, AppState, Conclusion, SilverBullet, Battlecard, ShortlistedCompetitor, ReferenceAnalysis } from '../types';

const API_BASE_URL = './'; // Relative to the application sub-path (/ca/)

export const fetchProductDetails = async (name: string, url: string, language: 'de' | 'en'): Promise<Product> => {
    const response = await fetch(`${API_BASE_URL}api/fetchProductDetails`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name, url, language }),
    });
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
};

export const fetchStep1Data = async (startUrl: string, language: 'de' | 'en'): Promise<{ products: Product[], target_industries: TargetIndustry[] }> => {
    const response = await fetch(`${API_BASE_URL}api/fetchStep1Data`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ start_url: startUrl, language }),
    });
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
};

export const fetchStep2Data = async (products: Product[], industries: TargetIndustry[], language: 'de' | 'en'): Promise<{ keywords: Keyword[] }> => {
    const response = await fetch(`${API_BASE_URL}api/fetchStep2Data`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ products, industries, language }),
    });
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
};

export const fetchStep3Data = async (keywords: Keyword[], marketScope: string, language: 'de' | 'en'): Promise<{ competitor_candidates: CompetitorCandidate[] }> => {
    const response = await fetch(`${API_BASE_URL}api/fetchStep3Data`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ keywords, market_scope: marketScope, language }),
    });
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
};

export const fetchStep4Data = async (company: AppState['company'], competitors: CompetitorCandidate[], language: 'de' | 'en'): Promise<{ analyses: Analysis[] }> => {
    const response = await fetch(`${API_BASE_URL}api/fetchStep4Data`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ company, competitors, language }),
    });
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
};

export const reanalyzeCompetitor = async (company: AppState['company'], competitor: CompetitorCandidate, manualUrls: string[]): Promise<Analysis> => {
    const response = await fetch(`${API_BASE_URL}api/reanalyzeCompetitor`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ company, competitor, manual_urls: manualUrls }),
    });
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
};

export const fetchStep5Data_SilverBullets = async (company: AppState['company'], analyses: Analysis[], language: 'de' | 'en'): Promise<{ silver_bullets: SilverBullet[] }> => {
    const response = await fetch(`${API_BASE_URL}api/fetchStep5Data_SilverBullets`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ company, analyses, language }),
    });
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
};

export const fetchStep6Data_Conclusion = async (company: AppState['company'], products: Product[], industries: TargetIndustry[], analyses: Analysis[], silver_bullets: SilverBullet[], language: 'de' | 'en'): Promise<{ conclusion: Conclusion }> => {
    const response = await fetch(`${API_BASE_URL}api/fetchStep6Data_Conclusion`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ company, products, industries, analyses, silver_bullets, language }),
    });
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
};

export const fetchStep7Data_Battlecards = async (company: AppState['company'], analyses: Analysis[], silver_bullets: SilverBullet[], language: 'de' | 'en'): Promise<{ battlecards: Battlecard[] }> => {
    const response = await fetch(`${API_BASE_URL}api/fetchStep7Data_Battlecards`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ company, analyses, silver_bullets, language }),
    });
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
};

export const fetchStep8Data_ReferenceAnalysis = async (competitors: ShortlistedCompetitor[], language: 'de' | 'en'): Promise<{ reference_analysis: ReferenceAnalysis[], groundingMetadata: any[] }> => {
    const response = await fetch(`${API_BASE_URL}api/fetchStep8Data_ReferenceAnalysis`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ competitors, language }),
    });
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
};
