<?php
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/ai/LocalAIApi.php';

$prompt = "Generate 3 professional blog posts for an APK/Android app store website. 
Return ONLY a JSON array of objects. Each object must have:
- 'title': A catchy title.
- 'slug': A URL-friendly slug.
- 'content': Detailed HTML content (using <p>, <h2>, <ul>, etc.) at least 300 words.
Topics:
1. Top 5 Productivity Apps for 2026.
2. How to Safely Install APKs on Your Android Device.
3. The Future of Mobile Gaming: Trends in 2026.

Language: Indonesian.";

$response = LocalAIApi::createResponse([
    'input' => [
        ['role' => 'system', 'content' => 'You are a professional tech blogger and SEO expert.'],
        ['role' => 'user', 'content' => $prompt],
    ],
]);

if (!empty($response['success'])) {
    $posts = LocalAIApi::decodeJsonFromResponse($response);
    if (is_array($posts)) {
        $db = db();
        foreach ($posts as $post) {
            try {
                $stmt = $db->prepare("INSERT INTO posts (title, slug, content, status) VALUES (?, ?, ?, 'published')");
                $stmt->execute([$post['title'], $post['slug'], $post['content']]);
                echo "Inserted: " . $post['title'] . "\n";
            } catch (Exception $e) {
                echo "Error inserting " . $post['title'] . ": " . $e->getMessage() . "\n";
            }
        }
    } else {
        echo "Failed to decode JSON from AI response.\n";
        // Attempt to extract text if JSON decoding fails directly
        $text = LocalAIApi::extractText($response);
        echo "Raw AI Text: " . substr($text, 0, 500) . "...\n";
    }
} else {
    echo "AI Request failed: " . ($response['error'] ?? 'Unknown error') . "\n";
}

