import { Router } from 'express';
import path from 'path';
import fs from 'fs';
import { STATE_DIR } from '../services/database.js';
const MODEL_STATE_FILE = path.join(STATE_DIR, 'model.json');
function ensureStateDir() {
    if (!fs.existsSync(STATE_DIR)) {
        fs.mkdirSync(STATE_DIR, { recursive: true });
    }
}
function readModelState() {
    try {
        if (!fs.existsSync(MODEL_STATE_FILE)) {
            return { recent: [], favorite: [] };
        }
        const data = fs.readFileSync(MODEL_STATE_FILE, 'utf-8');
        const parsed = JSON.parse(data);
        return {
            recent: Array.isArray(parsed.recent) ? parsed.recent : [],
            favorite: Array.isArray(parsed.favorite) ? parsed.favorite : [],
            variant: typeof parsed.variant === 'object' && parsed.variant !== null ? parsed.variant : {},
        };
    }
    catch (err) {
        console.error('[model-state] Failed to read model state:', err);
        return { recent: [], favorite: [] };
    }
}
function writeModelState(state) {
    try {
        ensureStateDir();
        fs.writeFileSync(MODEL_STATE_FILE, JSON.stringify(state, null, 2), 'utf-8');
    }
    catch (err) {
        console.error('[model-state] Failed to write model state:', err);
        throw err;
    }
}
function toggleFavorite(model) {
    const state = readModelState();
    const exists = state.favorite.some((f) => f.providerID === model.providerID && f.modelID === model.modelID);
    if (exists) {
        // Remove from favorites
        state.favorite = state.favorite.filter((f) => f.providerID !== model.providerID || f.modelID !== model.modelID);
    }
    else {
        // Add to favorites
        state.favorite = [model, ...state.favorite];
    }
    writeModelState(state);
    return state;
}
const router = Router();
// GET /__model-state - read model state
router.get('/', (_req, res) => {
    try {
        const state = readModelState();
        res.json({ recent: state.recent, favorite: state.favorite });
    }
    catch (err) {
        console.error('[model-state] Failed to get model state:', err);
        res.status(500).json({ error: 'Failed to read model state' });
    }
});
// POST /__model-state/favorite - toggle favorite
router.post('/favorite', (req, res) => {
    try {
        const model = req.body;
        if (!model.providerID || !model.modelID) {
            res.status(400).json({ error: 'providerID and modelID required' });
            return;
        }
        const state = toggleFavorite(model);
        res.json({ recent: state.recent, favorite: state.favorite });
    }
    catch (err) {
        console.error('[model-state] Failed to toggle favorite:', err);
        res.status(500).json({ error: 'Failed to update model state' });
    }
});
export default router;
