<?php
declare(strict_types=1);

require dirname(__DIR__) . '/app/bootstrap.php';

use App\Services\DiarWorkspaceNavigation;

$root = dirname(__DIR__);
$checks = [];
$failures = [];

$check = static function (bool $condition, string $code) use (&$checks, &$failures): void {
    $checks[] = $code;
    if (!$condition) { $failures[] = $code; }
};
$source = static function (string $relative) use ($root): string {
    return (string)@file_get_contents($root . '/' . $relative);
};

$requiredFiles = [
    'app/Controllers/DiarWorkspaceController.php',
    'app/Controllers/DiarCasesController.php',
    'app/Repositories/DiarCasesRepository.php',
    'app/Services/DiarWorkspaceNavigation.php',
    'app/Views/diar_workspace/portal.php',
    'app/Views/diar_workspace/module.php',
    'app/Views/diar_command_center/cases.php',
    'public/assets/css/diar-workspace.css',
    'public/assets/css/diar-cases.css',
    'tools/diar-6b-r2-live-acceptance.php',
    'tools/diar-6b-r2-role-templates.php',
    'tools/diar-6b-r2-role-rollback.php',
];
foreach ($requiredFiles as $file) {
    $check(is_file($root . '/' . $file), 'FILE_' . strtoupper(str_replace(['/', '.', '-'], '_', $file)));
}

$router = $source('public/index.php');
$config = $source('config/access_control.php');
$layout = $source('app/Views/layouts/main.php');
$tabs = $source('app/Views/diar_command_center/_tabs.php');
$executive = $source('app/Controllers/DiarExecutiveOverviewController.php');
$repo = $source('app/Repositories/DiarCasesRepository.php');
$casesController = $source('app/Controllers/DiarCasesController.php');
$casesView = $source('app/Views/diar_command_center/cases.php');
$roleInstaller = $source('tools/diar-6b-r2-role-templates.php');

$check(substr_count($router, 'DIAR_6B_2_R2_CONTROLLER_USE') === 2, 'ROUTER_CONTROLLER_IMPORTS');
$check(substr_count($router, 'DIAR_6B_2_R2_ROUTES') === 1, 'ROUTER_ROUTE_MARKER');
foreach (['diar-portal','diar-statistics','diar-cases','diar-investigation-workspace','diar-reports','diar-governance'] as $route) {
    $check(substr_count($router, "case '{$route}':") === 1, 'ROUTE_' . strtoupper(str_replace('-', '_', $route)));
}
$check(strpos($router, 'diar-cases-export') === false, 'NO_PREMATURE_CASE_EXPORT_ROUTE');

$check(substr_count($config, 'DIAR_6B_2_R2_PERMISSIONS') === 1, 'PERMISSION_MARKER');
foreach (['diar.portal.view','diar.executive.view','diar.statistics.view','diar.cases.view','diar.reports.view','diar.governance.view'] as $permission) {
    $check(substr_count($config, "'{$permission}' =>") === 1, 'PERMISSION_' . strtoupper(str_replace('.', '_', $permission)));
}

foreach ([
    'DIAR_6B_2_R2_LAYOUT_CAPABILITY',
    'DIAR_6B_2_R2_PAGE_TITLES',
    'DIAR_6B_2_R2_SINGLE_NAV',
    'DIAR_6B_2_R2_SIDEBAR_GROUP',
] as $marker) {
    $check(strpos($layout, $marker) !== false, 'LAYOUT_' . $marker);
}
$check(strpos($layout, "['page' => 'diar-portal'") !== false, 'SINGLE_DIAR_PORTAL_NAV');
$check(strpos($layout, "['page' => 'diar-rules'") === false, 'NO_DIRECT_RULES_SIDEBAR');
$check(strpos($layout, "['page' => 'diar-investigations'") === false, 'NO_DIRECT_INVESTIGATION_SIDEBAR');
$check(strpos($layout, "['page' => 'diar-command-center'") === false, 'NO_DIRECT_COMMAND_SIDEBAR');

$check(substr_count($tabs, 'DIAR_6B_2_R2_ROLE_NAV') === 1, 'ROLE_NAV_MARKER');
$check(strpos($tabs, 'DiarWorkspaceNavigation::modules') !== false, 'ROLE_AWARE_NAV_SERVICE');
$check(substr_count($executive, 'DIAR_6B_2_R2_EXECUTIVE_ACL') === 1, 'EXECUTIVE_ACL_MARKER');
$check(strpos($executive, "AccessControl::allows('diar.executive.view')") !== false, 'EXECUTIVE_PERMISSION');
$check(strpos($executive, "AccessControl::allows('diar.command.view')") !== false, 'EXECUTIVE_LEGACY_COMPATIBILITY');

$check(count(DiarWorkspaceNavigation::definitions()) === 6, 'SIX_WORK_AREAS');
$check(count(DiarWorkspaceNavigation::roleTemplates()) === 6, 'SIX_ROLE_TEMPLATES');
$check(count(DiarWorkspaceNavigation::reportSheets()) === 12, 'TWELVE_REPORT_SHEETS');

$check(strpos($casesController, "AccessControl::allows('diar.cases.view')") !== false, 'CASES_PERMISSION');
$check(strpos($casesController, 'function export(') === false, 'NO_PREMATURE_EXPORT_METHOD');
$check(strpos($casesView, "url_to('diar-reports')") !== false, 'CASES_LINK_TO_REPORT_CENTER');
$check(strpos($casesView, 'diar-cases-export') === false, 'CASES_NO_EXPORT_LINK');

$check(strpos($repo, 'DASH_DIAR_MONTH_SNAPSHOTS') !== false, 'CASES_MONTH_SNAPSHOT_SOURCE');
$check(strpos($repo, 'DASH_DIAR_MONTH_CASES') !== false, 'CASES_MONTH_CASE_SOURCE');
$check(strpos($repo, 'STORE_CODE NOT IN (56,57)') !== false || strpos($repo, 'STORE_CODE IN (56,57)') !== false, 'EXCLUDED_STORE_GUARD');
$check(strpos($repo, "'read_only' => true") !== false, 'READ_ONLY_CONTRACT');
$check(strpos($repo, "'database_link' => false") !== false, 'NO_DB_LINK_CONTRACT');
$check(strpos($repo, 'Database::execute(') === false, 'CASES_NO_EXECUTE');
$check(strpos($repo, 'Database::executeTransaction(') === false, 'CASES_NO_TRANSACTION');
$check(!preg_match('/\b(INSERT|UPDATE|DELETE|MERGE|TRUNCATE)\s+(INTO|FROM|TABLE|DASH_)/i', $repo), 'CASES_NO_DML_SQL');

$check(strpos($roleInstaller, "'user_assignments' => 'NONE'") !== false, 'ROLE_INSTALL_NO_USER_ASSIGNMENT');
$check(strpos($roleInstaller, 'DASH_ACL_USER_ROLES') === false || strpos($roleInstaller, 'SELECT COUNT(*)') !== false, 'ROLE_INSTALL_NO_USER_ROLE_DML');
$check(strpos($roleInstaller, "'acl_writes' => 'ROLE_TEMPLATES_ONLY'") !== false, 'ROLE_INSTALL_BOUNDARY');

foreach ([
    'app/Views/diar_investigations/index.php' => 'DIAR_6B_2_R2_INVESTIGATION_INDEX_NAV',
    'app/Views/diar_investigations/detail.php' => 'DIAR_6B_2_R2_INVESTIGATION_DETAIL_NAV',
    'app/Views/diar_rules/index.php' => 'DIAR_6B_2_R2_RULES_NAV',
] as $file => $marker) {
    $check(strpos($source($file), $marker) !== false, 'VIEW_NAV_' . strtoupper(str_replace(['/', '.'], '_', $file)));
}

if ($failures !== []) {
    fwrite(STDERR, 'DIAR_6B_2_R2_1_STATIC_QA|FAIL|CHECKS=' . count($checks) . '|FAILED=' . implode(',', $failures) . PHP_EOL);
    exit(1);
}

echo 'DIAR_6B_2_R2_1_STATIC_QA|PASS|CHECKS=' . count($checks)
    . '|MODULES=6|ROLES=6|REPORT_SHEETS=12|READ_ONLY=PASS|ROLE_SEPARATION=PASS' . PHP_EOL;
