const express = require('express'); const { spawn } = require('child_process'); const bodyParser = require('body-parser'); const cors = require('cors'); const fs = require('fs'); const path = require('path'); const app = express(); const PORT = 3001; // Node.js Server läuft auf einem anderen Port als React (3000) // Middleware app.use(cors()); // Ermöglicht Cross-Origin-Requests von der React-App app.use(bodyParser.json()); // Parst JSON-Anfragen // API-Endpunkt für generateSearchStrategy app.post('/api/generate-search-strategy', async (req, res) => { console.log(`[${new Date().toISOString()}] HIT: /api/generate-search-strategy`); const { referenceUrl, contextContent } = req.body; if (!referenceUrl || !contextContent) { console.error('Validation Error: Missing referenceUrl or contextContent.'); return res.status(400).json({ error: 'Missing referenceUrl or contextContent' }); } const tempContextFilePath = path.join(__dirname, 'tmp', `context_${Date.now()}.md`); const tmpDir = path.join(__dirname, 'tmp'); if (!fs.existsSync(tmpDir)) { fs.mkdirSync(tmpDir); } try { fs.writeFileSync(tempContextFilePath, contextContent); console.log(`Successfully wrote context to ${tempContextFilePath}`); const pythonExecutable = path.join(__dirname, '..', '.venv', 'bin', 'python3'); const pythonScript = path.join(__dirname, '..', 'market_intel_orchestrator.py'); const scriptArgs = [pythonScript, '--mode', 'generate_strategy', '--reference_url', referenceUrl, '--context_file', tempContextFilePath]; console.log(`Spawning command: ${pythonExecutable}`); console.log(`With arguments: ${JSON.stringify(scriptArgs)}`); const pythonProcess = spawn(pythonExecutable, scriptArgs, { env: { ...process.env, PYTHONPATH: path.join(__dirname, '..', '.venv', 'lib', 'python3.11', 'site-packages') } }); let pythonOutput = ''; let pythonError = ''; pythonProcess.stdout.on('data', (data) => { pythonOutput += data.toString(); }); pythonProcess.stderr.on('data', (data) => { pythonError += data.toString(); }); pythonProcess.on('close', (code) => { console.log(`Python script finished with exit code: ${code}`); console.log(`--- STDOUT ---`); console.log(pythonOutput); console.log(`--- STDERR ---`); console.log(pythonError); console.log(`----------------`); fs.unlinkSync(tempContextFilePath); if (code !== 0) { console.error(`Python script exited with error.`); return res.status(500).json({ error: 'Python script failed', details: pythonError }); } try { const result = JSON.parse(pythonOutput); res.json(result); } catch (parseError) { console.error('Failed to parse Python output as JSON:', parseError); res.status(500).json({ error: 'Invalid JSON from Python script', rawOutput: pythonOutput, details: pythonError }); } }); pythonProcess.on('error', (err) => { console.error('FATAL: Failed to start python process itself.', err); if (fs.existsSync(tempContextFilePath)) { fs.unlinkSync(tempContextFilePath); } res.status(500).json({ error: 'Failed to start Python process', details: err.message }); }); } catch (writeError) { console.error('Failed to write temporary context file:', writeError); res.status(500).json({ error: 'Failed to write temporary file', details: writeError.message }); } }); // Start des Servers app.listen(PORT, () => { console.log(`Node.js API Bridge running on http://localhost:${PORT}`); });