import { Phase1Data, Phase2Data, Phase3Data, Phase4Data, Phase6Data, Phase7Data, Phase8Data, Phase9Data, Language, ProjectHistoryItem } from "./types";

const API_BASE_URL = './api'; // Relative path to respect Nginx /gtm/ routing

const callApi = async <T>(endpoint: string, mode: string, payload: object): Promise<T> => {
    try {
        const response = await fetch(`${API_BASE_URL}/${endpoint}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ mode, ...payload }),
        });

        if (!response.ok) {
            const errorBody = await response.text();
            console.error(`API call failed with status ${response.status}:`, errorBody);
            throw new Error(`Request failed: ${response.statusText}`);
        }
        return await response.json() as T;
    } catch (error) {
        console.error('An error occurred during the API call:', error);
        throw new Error('API call failed. Check the server logs for more details.');
    }
};


// --- Phase 1: Product Analysis ---
export const analyzeProduct = async (productInput: string, lang: Language): Promise<Phase1Data> => {
    return callApi<Phase1Data>('run', 'phase1', { productInput, lang });
};

// --- Phase 2: ICP Discovery ---
export const discoverICPs = async (phase1Data: Phase1Data, lang: Language, projectId: string): Promise<Phase2Data> => {
    return callApi<Phase2Data>('run', 'phase2', { phase1Data, lang, projectId });
};

// --- Phase 3: Whale Hunting ---
export const huntWhales = async (phase2Data: Phase2Data, lang: Language, projectId: string): Promise<Phase3Data> => {
    return callApi<Phase3Data>('run', 'phase3', { phase2Data, lang, projectId });
};

// --- Phase 4: Strategy ---
export const developStrategy = async (phase3Data: Phase3Data, phase1Data: Phase1Data, lang: Language, projectId: string): Promise<Phase4Data> => {
    return callApi<Phase4Data>('run', 'phase4', { phase3Data, phase1Data, lang, projectId });
};

// --- Phase 5: Assets & Report ---
export const generateAssets = async (
    phase4Data: Phase4Data, 
    phase3Data: Phase3Data, 
    phase2Data: Phase2Data, 
    phase1Data: Phase1Data, 
    lang: Language,
    projectId: string
): Promise<{ report: string }> => {
    return callApi<{ report: string }>('run', 'phase5', { phase4Data, phase3Data, phase2Data, phase1Data, lang, projectId });
};

// --- Phase 6: Sales Enablement & Visuals ---
export const generateSalesEnablement = async (
    phase4Data: Phase4Data,
    phase3Data: Phase3Data,
    phase1Data: Phase1Data,
    lang: Language,
    projectId: string
): Promise<Phase6Data> => {
    return callApi<Phase6Data>('run', 'phase6', { phase4Data, phase3Data, phase1Data, lang, projectId });
};

// --- Phase 7: Vertical Landing Page Copy ---
export const generateLandingPageCopy = async (
    phase4Data: Phase4Data,
    phase2Data: Phase2Data,
    lang: Language,
    projectId: string
): Promise<Phase7Data> => {
    return callApi<Phase7Data>('run', 'phase7', { phase4Data, phase2Data, lang, projectId });
};

// --- Phase 8: Business Case Builder ---
export const buildBusinessCase = async (
    phase2Data: Phase2Data,
    phase1Data: Phase1Data,
    lang: Language,
    projectId: string
): Promise<Phase8Data> => {
    return callApi<Phase8Data>('run', 'phase8', { phase2Data, phase1Data, lang, projectId });
};

// --- Phase 9: Feature-to-Value Translator ---
export const translateTech = async (
    phase1Data: Phase1Data,
    phase4Data: Phase4Data,
    lang: Language,
    projectId: string
): Promise<Phase9Data> => {
    return callApi<Phase9Data>('run', 'phase9', { phase1Data, phase4Data, lang, projectId });
};

export const translateReportToEnglish = async (reportMarkdown: string): Promise<{ report: string }> => {
    return callApi<{ report: string }>('run', 'translate', { reportMarkdown });
};

export const generateConceptImage = async (prompt: string, referenceImagesBase64?: string[], aspectRatio?: string): Promise<string> => {
    const result = await callApi<{ imageBase64: string }>('run', 'image', { prompt, referenceImagesBase64, aspectRatio });
    return result.imageBase64;
};

export const listSessions = async (): Promise<{ projects: ProjectHistoryItem[] }> => {
    return callApi('run', 'list_history', {});
};

export const loadSession = async (projectId: string): Promise<any> => {
    return callApi('run', 'load_history', { projectId });
};

export const deleteSession = async (projectId: string): Promise<any> => {
    return callApi('run', 'delete_session', { projectId });
};

export const updateSpecs = async (projectId: string, specs: any): Promise<any> => {
    return callApi('run', 'update_specs', { projectId, specs });
};