<?php
// ─────────────────────────────────────────────
// api/stories.php  —  Story-Varianten generieren
// ─────────────────────────────────────────────

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/ai_engine.php';

c2c_cors_headers();
require_api_token();

$clientId   = (int)($_GET['client_id']   ?? 0);
$analysisId = (int)($_GET['analysis_id'] ?? 0);

if (!$clientId || !$analysisId) {
    json_response(['error' => 'client_id und analysis_id erforderlich'], 422);
}

try {
    $stories = C2CAIEngine::generateStories($clientId, $analysisId);
    json_response([
        'success' => true,
        'count'   => count($stories),
        'stories' => array_map(fn($s) => [
            'id'          => $s['id'],
            'variant_key' => $s['variant_key'],
            'title'       => $s['title'],
            'subtitle'    => $s['subtitle'],
            'teaser'      => $s['teaser'],
        ], $stories),
    ]);
} catch (Exception $e) {
    error_log("Stories Error client $clientId: " . $e->getMessage());
    json_response(['error' => $e->getMessage()], 500);
}
