<?php
declare(strict_types=1);

$examplesRoot = dirname(__DIR__, 3);
require_once $examplesRoot . '/platform/shared_session.php';
require_once $examplesRoot . '/platform/footer.php';

$crashSrc = $examplesRoot . '/crash_reporter/backend/src';
$configPath = __DIR__ . '/../config/config.php';
if (!is_file($configPath)) {
    $configPath = __DIR__ . '/../config/config.example.php';
}
$config = require $configPath;

platform_start_session(
    $config['session_name'] ?? 'ac_crash_sess',
    $config['session_cookie_path'] ?? '/app/androidcast_project'
);

foreach (['Database.php', 'Rbac.php', 'Auth.php', 'UserRepository.php', 'AnalyticsHead.php'] as $f) {
    require_once $crashSrc . '/' . $f;
}

require_once __DIR__ . '/BuildRepository.php';
require_once __DIR__ . '/BuildRunner.php';

function cfg(string $key, $default = null) {
    global $config;
    $parts = explode('.', $key);
    $v = $config;
    foreach ($parts as $p) {
        if (!is_array($v) || !array_key_exists($p, $v)) {
            return $default;
        }
        $v = $v[$p];
    }
    return $v;
}

function h(mixed $s): string {
    if ($s === null || $s === false) {
        return '';
    }
    return htmlspecialchars((string) $s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function json_out(array $data, int $code = 200): void {
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

function assets_base(): string {
    return rtrim((string) cfg('links.crashes', '/app/androidcast_project/crashes/'), '/');
}

/** @return 'running'|'passed'|'failed' */
function build_status_kind(string $status): string {
    $s = strtolower(trim($status));
    if (in_array($s, ['running', 'queued'], true)) {
        return 'running';
    }
    if ($s === 'passed') {
        return 'passed';
    }
    return 'failed';
}

/** Inline status glyph: spinner (in progress), green check, or red alert triangle. */
function build_status_icon(string $status): string {
    $kind = build_status_kind($status);
    $labels = [
        'running' => 'In progress',
        'passed' => 'Succeeded',
        'failed' => 'Failed or cancelled',
    ];
    $label = h($labels[$kind] ?? 'Unknown');
    if ($kind === 'running') {
        return '<span class="build-status-icon build-status-icon--running" role="img" aria-label="' . $label . '">'
            . '<span class="build-status-spinner"></span></span>';
    }
    if ($kind === 'passed') {
        return '<span class="build-status-icon build-status-icon--passed" role="img" aria-label="' . $label . '"></span>';
    }
    return '<span class="build-status-icon build-status-icon--failed" role="img" aria-label="' . $label . '">'
        . '<span class="build-status-fail-mark" aria-hidden="true">!</span></span>';
}
