<?php

declare(strict_types=1);

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

use App\Framework\LiveComponents\Observability\ComponentMetricsCollector;

$collector = new ComponentMetricsCollector();

// Test 6 DEBUG: HELP Comment Format
echo "Test 6 DEBUG: HELP Comment Format\n";
$collector->reset();
$collector->recordRender('test', 10.0);

$prometheus = $collector->exportPrometheus();
echo "Full Prometheus output:\n";
echo $prometheus . "\n";
echo "\nSearching for HELP lines:\n";
$lines = explode("\n", $prometheus);
foreach ($lines as $line) {
    if (str_contains($line, 'HELP')) {
        echo "Found: {$line}\n";
    }
}

echo "\n---\n\n";

// Test 7 DEBUG: TYPE Declaration Format
echo "Test 7 DEBUG: TYPE Declaration Format\n";
echo "Searching for TYPE lines:\n";
foreach ($lines as $line) {
    if (str_contains($line, 'TYPE')) {
        echo "Found: {$line}\n";
    }
}

echo "\n---\n\n";

// Test 11 DEBUG: Counter Suffix Validation
echo "Test 11 DEBUG: Counter Suffix Validation\n";
$collector->reset();
$collector->recordRender('test', 5.0);
$collector->recordAction('test', 'action', 10.0, true);

$prometheus = $collector->exportPrometheus();

echo "Searching for counter TYPE declarations:\n";
$lines = explode("\n", $prometheus);
foreach ($lines as $line) {
    if (preg_match('/^# TYPE ([a-z_]+) counter$/m', $line, $match)) {
        echo "Found counter: {$match[1]}\n";
        if (!str_ends_with($match[1], '_total')) {
            echo "  -> Missing '_total' suffix!\n";
        }
    }
}

echo "\n---\n\n";

// Test 12 DEBUG: Label Ordering
echo "Test 12 DEBUG: Label Ordering\n";
$collector->reset();
$collector->recordAction('test-component', 'submit-action', 15.0, true);

$prometheus = $collector->exportPrometheus();

echo "Checking metric lines:\n";
$lines = explode("\n", $prometheus);
foreach ($lines as $line) {
    if (preg_match('/^([a-z_]+)\{([^\}]+)\}/', $line, $match)) {
        echo "Metric: {$match[1]}\n";
        echo "Labels: {$match[2]}\n";

        preg_match_all('/([a-z_]+)="[^"]*"/', $match[2], $keyMatches);
        $keys = $keyMatches[1] ?? [];
        $sortedKeys = $keys;
        sort($sortedKeys);

        echo "Current order: " . implode(',', $keys) . "\n";
        echo "Expected order: " . implode(',', $sortedKeys) . "\n";
        echo "\n";
    }
}
