import fs from 'fs';
import path from 'path';

const DATA_DIR = path.join(process.cwd(), 'data');
const HISTORY_FILE = path.join(DATA_DIR, 'history.json');

// Ensure data dir exists
if (!fs.existsSync(DATA_DIR)) {
    fs.mkdirSync(DATA_DIR, { recursive: true });
}

export interface HistoryItem {
    id: string;
    url: string; // Base64 data URI for now, or local path served via public
    originalName: string;
    category: string;
    timestamp: number;
    mediaId?: string; // Whisk Media ID if available
}

export const history = {
    getAll: (category?: string): HistoryItem[] => {
        if (!fs.existsSync(HISTORY_FILE)) return [];
        try {
            const data = JSON.parse(fs.readFileSync(HISTORY_FILE, 'utf-8'));
            let items: HistoryItem[] = Array.isArray(data) ? data : [];

            if (category) {
                items = items.filter(i => i.category === category);
            }
            return items.sort((a, b) => b.timestamp - a.timestamp);
        } catch (e) {
            return [];
        }
    },

    add: (item: Omit<HistoryItem, 'timestamp'>) => {
        const items = history.getAll();
        const newItem: HistoryItem = { ...item, timestamp: Date.now() };
        items.unshift(newItem); // Add to top

        // Limit to 50 items per category? or total?
        // Let's keep total 100 for now.
        const trimmed = items.slice(0, 100);

        fs.writeFileSync(HISTORY_FILE, JSON.stringify(trimmed, null, 2));
        return newItem;
    },

    delete: (id: string) => {
        const items = history.getAll();
        const filtered = items.filter(i => i.id !== id);
        fs.writeFileSync(HISTORY_FILE, JSON.stringify(filtered, null, 2));
    }
};
