<?php

declare(strict_types=1);

$root = dirname(__DIR__);

function containsMarker(string $path, string $marker): bool
{
    return is_file($path) && strpos((string)file_get_contents($path), $marker) !== false;
}

$checks = [
    'controller' => is_file($root . '/app/Controllers/DiarRuleSettingsController.php'),
    'repository' => is_file($root . '/app/Repositories/DiarRuleSettingsRepository.php'),
    'view' => is_file($root . '/app/Views/diar_rules/index.php'),
    'css' => is_file($root . '/public/assets/css/diar-rules.css'),
    'js' => is_file($root . '/public/assets/js/diar-rules.js'),
    'apply_tool' => is_file($root . '/tools/diar4a-apply.php'),
    'acceptance_tool' => is_file($root . '/tools/diar4a-live-acceptance.php'),
    'dry_run_result_tool' => is_file($root . '/tools/diar4a-record-dry-run.php'),
    'router_controller_use' => containsMarker($root . '/public/index.php', 'use App\\Controllers\\DiarRuleSettingsController;'),
    'router_case' => containsMarker($root . '/public/index.php', "case 'diar-rules':"),
    'permission_contract' => containsMarker($root . '/config/access_control.php', "'diar.rules.view'"),
    'route_permission_contract' => containsMarker($root . '/config/access_control.php', "'diar-rules' =>"),
    'layout_navigation' => containsMarker($root . '/app/Views/layouts/main.php', "['page' => 'diar-rules'"),
    'layout_css' => containsMarker($root . '/app/Views/layouts/main.php', 'assets/css/diar-rules.css'),
    'layout_js' => containsMarker($root . '/app/Views/layouts/main.php', 'assets/js/diar-rules.js'),
    'version_contract' => containsMarker($root . '/DDB_VERSION.json', 'DIAR4A-R1-WINDOWS-NO-SHELL-SAFE-MERGE'),
];

$failed = [];
foreach ($checks as $key => $value) {
    if (!$value) {
        $failed[] = $key;
    }
}

$result = [
    'schema' => 'DIAR4A_LOCAL_FILE_TEST_V2',
    'status' => $failed === [] ? 'PASS' : 'FAIL',
    'checks' => $checks,
    'failed' => $failed,
    'application_integration' => 'MARKER_BASED_ATOMIC_MERGE',
];

echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($result['status'] === 'PASS' ? 0 : 1);
