<?php
declare(strict_types=1);

require_once __DIR__ . '/../bootstrap.php';

use Crawl\Lib\Database;
use Crawl\Services\CrawlManagerService;
use Crawl\Repositories\CrawlRunRepository;

function assertTrue(bool $condition, string $message): void
{
    if (!$condition) {
        throw new RuntimeException($message);
    }
}

function ensureProject(): int
{
    $db = Database::getInstance();
    $existing = $db->fetch('SELECT id FROM projects WHERE website_url = ? LIMIT 1', ['https://example.com']);
    if ($existing) {
        return (int)$existing['id'];
    }

    return $db->insert('projects', [
        'business_name' => 'Crawl Smoke Test Site',
        'website_url' => 'https://example.com',
        'target_audience' => 'Engineers and marketers',
        'content_intent' => 'Audit website content and links',
        'brand_positioning' => 'Audit site for SEO and quality',
        'tone_voice' => 'professional',
        'brand_dos' => 'Use clear language',
        'brand_donts' => 'Avoid duplicate content',
        'pov_type' => 'third_person',
        'seo_philosophy' => 'Keep pages crawlable and structured',
        'compliance_rules' => 'Must follow accessibility guidelines',
        'brand_reference_style' => 'Consistent, modern tone',
        'cta_style' => 'Direct and helpful',
        'no_no_words' => 'spam, fake, bogus',
        'guideline_doc_url' => 'https://example.com/guidelines',
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s'),
    ]);
}

function runSmokeTests(): void
{
    $projectId = ensureProject();
    $service = new CrawlManagerService();
    $runs = new CrawlRunRepository();

    $run = $service->startRun($projectId, 'https://example.com', 1, 1, 1, 'Mozilla/5.0');
    $runId = (int)($run['crawl_run_id'] ?? 0);

    assertTrue($runId > 0, 'Expected a crawl run to be created');
    assertTrue(($run['status'] ?? null) === 'running', 'Expected crawl to start in running state');

    $latest = $runs->latestForProject($projectId);
    assertTrue(is_array($latest), 'Expected latest run record');
    assertTrue((int)($latest['id'] ?? 0) === $runId, 'Expected latest run ID to match created run');
    assertTrue(($latest['status'] ?? null) === 'running', 'Expected latest run status to be running');

    echo "Smoke API tests passed.\n";
}

try {
    runSmokeTests();
} catch (Throwable $e) {
    fwrite(STDERR, 'Smoke API test failed: ' . $e->getMessage() . "\n");
    exit(1);
}
