<?php
// ═══════════════════════════════════════════════════════════
//  FICTION IGNITION — api/generate/index.php
//  POST /api/generate/
//  Tier-enforced prompt generation via Anthropic Claude API
// ═══════════════════════════════════════════════════════════

declare(strict_types=1);

require_once __DIR__ . '/../lib/config.php';

fi_json_headers();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') fi_error('Method not allowed.', 405);

// ── Auth & tier check ──────────────────────────────────────
$session = fi_get_session();
if (!$session) fi_error('Please sign in to generate prompts.', 401);

$tier = $session['tier'];
$info = TIERS[$tier] ?? TIERS['free'];

// Check daily limit
$used  = fi_prompts_used_today($session['id']);
$limit = $info['daily_limit'];

if ($limit !== PHP_INT_MAX && $used >= $limit) {
    fi_error(
        "You've used all {$limit} prompts for today on the {$info['label']} plan. Upgrade for more!",
        429
    );
}

// ── Input validation ───────────────────────────────────────
$input      = json_decode(file_get_contents('php://input'), true) ?? [];
$genre      = trim($input['genre'] ?? '');
$customGenre = trim($input['custom_genre'] ?? '');

if ($customGenre && !$info['custom_genre']) {
    fi_error('Custom genres require an Author Pro subscription.', 403);
}

$genreLabel = $customGenre ?: $genre;
if (!$genreLabel) fi_error('Genre is required.');
if (strlen($genreLabel) > 100) fi_error('Genre label is too long.');

// ── Choose model based on tier ─────────────────────────────
$model = $info['advanced_ai']
    ? 'claude-opus-4-5'        // Author Pro gets Opus
    : 'claude-haiku-4-5-20251001';  // All other tiers get Haiku (fast, cheap)

// ── System prompt ──────────────────────────────────────────
$systemPrompt = <<<PROMPT
You are Fiction Ignition, an AI writing prompt generator. Your sole purpose is to generate a single, vivid, specific 1–2 sentence story prompt for the given genre.

Rules:
- Make it specific: name a setting, a detail, a tension — not generic concepts
- Make it immediately inspiring — the writer should feel the story beginning to form
- Do NOT include any preamble, explanation, labels, or quotation marks
- Return ONLY the prompt text itself, nothing else
- Length: 25–60 words
PROMPT;

// ── Call Anthropic ─────────────────────────────────────────
$apiKey = env('ANTHROPIC_API_KEY');
if (!$apiKey) fi_error('Server configuration error.', 500);

$requestBody = json_encode([
    'model'      => $model,
    'max_tokens' => 200,
    'system'     => $systemPrompt,
    'messages'   => [
        ['role' => 'user', 'content' => "Genre: {$genreLabel}\n\nGenerate a story prompt."]
    ],
]);

$ch = curl_init('https://api.anthropic.com/v1/messages');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $requestBody,
    CURLOPT_TIMEOUT        => 20,
    CURLOPT_HTTPHEADER     => [
        'x-api-key: '         . $apiKey,
        'anthropic-version: 2023-06-01',
        'content-type: application/json',
    ],
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr  = curl_error($ch);
curl_close($ch);

if ($curlErr) fi_error('Network error generating prompt. Please try again.', 503);

$data = json_decode($response, true);
if ($httpCode !== 200 || empty($data['content'][0]['text'])) {
    error_log('Anthropic API error: ' . $response);
    fi_error('Failed to generate prompt. Please try again.', 503);
}

$prompt = trim($data['content'][0]['text']);

// ── Record usage ───────────────────────────────────────────
fi_increment_prompts($session['id']);

fi_ok([
    'prompt'     => $prompt,
    'genre'      => $genreLabel,
    'model_used' => $model,
    'prompts_left' => $limit === PHP_INT_MAX ? null : max(0, $limit - $used - 1),
]);
