const express = require('express');
const router = express.Router();

/**
 * The Forge — AI Knowledge Assistant
 * Trinity Console module for querying Firefrost documentation
 * via Dify RAG + Gemma 4 on TX1
 * 
 * Chronicler #82 | April 12, 2026
 */

const DIFY_API_URL = process.env.DIFY_API_URL || 'http://38.68.14.26:5001';
const DIFY_APP_KEY = process.env.DIFY_APP_KEY || 'app-forge-trinity-console-key';

// GET /admin/forge — The Forge chat interface
router.get('/', (req, res) => {
    res.render('admin/forge/index', {
        title: 'The Forge',
        currentPath: '/forge',
        adminUser: req.user
    });
});

// POST /admin/forge/chat — Proxy to Dify streaming API
router.post('/chat', async (req, res) => {
    const { query, conversation_id } = req.body;
    
    if (!query || !query.trim()) {
        return res.status(400).json({ error: 'Query is required' });
    }

    const userId = `trinity-${req.user?.id || 'unknown'}`;

    try {
        // Set up SSE headers
        res.setHeader('Content-Type', 'text/event-stream');
        res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('Connection', 'keep-alive');
        res.setHeader('X-Accel-Buffering', 'no');

        const response = await fetch(`${DIFY_API_URL}/v1/chat-messages`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${DIFY_APP_KEY}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                inputs: {},
                query: query.trim(),
                response_mode: 'streaming',
                conversation_id: conversation_id || '',
                user: userId
            })
        });

        if (!response.ok) {
            const errText = await response.text();
            console.error('[Forge] Dify API error:', response.status, errText);
            res.write(`data: ${JSON.stringify({ event: 'error', message: 'The Forge is temporarily unavailable.' })}\n\n`);
            return res.end();
        }

        // Pipe the SSE stream from Dify to the client
        const reader = response.body.getReader();
        const decoder = new TextDecoder();

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            const chunk = decoder.decode(value, { stream: true });
            res.write(chunk);
        }

        res.end();
    } catch (err) {
        console.error('[Forge] Chat error:', err);
        res.write(`data: ${JSON.stringify({ event: 'error', message: 'Connection to The Forge failed.' })}\n\n`);
        res.end();
    }
});

module.exports = router;
