import { useEffect, useState, useCallback } from 'react';
import {
    fetchEvolverStatus,
    fetchEvolverHistory,
    fetchLottoTasks,
    fetchLottoLogs,
} from '../../../api';


function mergeActivityStream({ logs, tasks, evolverEvents }) {
    const stream = [];
    for (const l of logs.items || []) {
        stream.push({ ts: l.created_at, kind: 'log', payload: l });
    }
    for (const t of tasks.items || tasks.tasks || []) {
        stream.push({ ts: t.created_at, kind: 'task', payload: t });
    }
    for (const e of evolverEvents) {
        stream.push({ ts: e.created_at, kind: 'evolver', payload: e });
    }
    stream.sort((a, b) => (b.ts || '').localeCompare(a.ts || ''));
    return stream;
}


export function useEvolverApi({ days = 7, weeks = 12 } = {}) {
    const [status, setStatus] = useState(null);
    const [history, setHistory] = useState({ items: [] });
    const [activity, setActivity] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    const refetch = useCallback(async () => {
        setLoading(true);
        setError(null);
        try {
            const [s, h, t, l] = await Promise.all([
                fetchEvolverStatus(),
                fetchEvolverHistory(weeks),
                fetchLottoTasks({ days }),
                fetchLottoLogs({ days }),
            ]);
            setStatus(s);
            setHistory(h);
            setActivity(mergeActivityStream({
                logs: l,
                tasks: t,
                evolverEvents: h.items || [],
            }));
        } catch (e) {
            setError(e);
        } finally {
            setLoading(false);
        }
    }, [days, weeks]);

    useEffect(() => { refetch(); }, [refetch]);

    return { status, history, activity, loading, error, refetch };
}
