<?php

declare(strict_types=1);

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\LiveComponents\Observability\ComponentMetricsCollector;

$collector = new ComponentMetricsCollector();

// Test 4: Performance Tab Data - DEBUG
echo "Test 4 DEBUG: Performance Tab Data\n";
$collector->reset();

$collector->recordRender('widget-1', 120.5, false);
$collector->recordRender('widget-1', 5.2, true);
$collector->recordRender('widget-2', 80.3, false);
$collector->recordAction('widget-1', 'loadData', 200.0, true);
$collector->recordAction('widget-1', 'refresh', 15.0, true);

$summary = $collector->getSummary();

echo "Expected: total_renders=3, total_actions=2, cache_hits=1, cache_misses=2\n";
echo "Got: total_renders={$summary['total_renders']}, total_actions={$summary['total_actions']}, ";
echo "cache_hits={$summary['cache_hits']}, cache_misses={$summary['cache_misses']}\n";
echo "Full summary: " . json_encode($summary, JSON_PRETTY_PRINT) . "\n\n";

// Test 14: Timestamp Tracking - DEBUG
echo "Test 14 DEBUG: Timestamp Tracking\n";
$collector->reset();

$collector->recordAction('timeline-test', 'action1', 10.0);
usleep(10000); // 10ms delay
$collector->recordAction('timeline-test', 'action2', 15.0);

$metrics = $collector->getMetrics();

$metric1 = $metrics['livecomponent_actions_total{action=action1,component_id=timeline-test,status=success}'] ?? null;
$metric2 = $metrics['livecomponent_actions_total{action=action2,component_id=timeline-test,status=success}'] ?? null;

echo "Metric 1 exists: " . ($metric1 !== null ? 'yes' : 'no') . "\n";
echo "Metric 2 exists: " . ($metric2 !== null ? 'yes' : 'no') . "\n";

if ($metric1 && $metric2) {
    echo "Metric 1 timestamp: " . ($metric1->timestamp !== null ? 'exists' : 'null') . "\n";
    echo "Metric 2 timestamp: " . ($metric2->timestamp !== null ? 'exists' : 'null') . "\n";

    if ($metric1->timestamp && $metric2->timestamp) {
        $ts1 = $metric1->timestamp->toTimestamp();
        $ts2 = $metric2->timestamp->toTimestamp();
        echo "Timestamp 1: {$ts1}\n";
        echo "Timestamp 2: {$ts2}\n";
        echo "Timestamp 2 > Timestamp 1: " . ($ts2 > $ts1 ? 'yes' : 'no') . "\n";
    }
}
echo "\n";

// Test 15: Special Characters - DEBUG
echo "Test 15 DEBUG: Special Character Escaping\n";
$collector->reset();

$collector->recordAction('form"test', 'validate\nfield', 10.0);

$prometheus = $collector->exportPrometheus();

echo "Checking for escaped double quote: form\\\"test\n";
echo "Found: " . (str_contains($prometheus, 'form\\"test') ? 'yes' : 'no') . "\n";

echo "Checking for escaped newline: validate\\nfield\n";
echo "Found: " . (str_contains($prometheus, 'validate\\nfield') ? 'yes' : 'no') . "\n";

echo "\nPrometheus excerpt:\n";
$lines = explode("\n", $prometheus);
foreach ($lines as $line) {
    if (str_contains($line, 'form') || str_contains($line, 'validate')) {
        echo $line . "\n";
    }
}
