#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

echo '[1/9] PHP syntax'
find backend -name '*.php' -print0 | while IFS= read -r -d '' f; do php -l "$f" >/dev/null; done
echo 'PASS: PHP syntax'

echo '[2/9] React/JSX syntax'
(cd frontend && NODE_PATH="$(npm root -g)" node - <<'NODE'
const fs=require('fs'),path=require('path'),ts=require('typescript');let bad=0,count=0;
function walk(d){for(const n of fs.readdirSync(d)){const p=path.join(d,n),s=fs.statSync(p);if(s.isDirectory())walk(p);else if(/\.(jsx|js)$/.test(n)){count++;const r=ts.transpileModule(fs.readFileSync(p,'utf8'),{compilerOptions:{jsx:ts.JsxEmit.ReactJSX,target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.ESNext},reportDiagnostics:true,fileName:p});if((r.diagnostics||[]).some(x=>x.category===ts.DiagnosticCategory.Error)){console.error('Syntax error:',p);bad++;}}}}walk('src');console.log(`PASS: parsed ${count} JS/JSX files`);process.exit(bad?1:0);
NODE
)

echo '[3/9] Frontend/API route consistency'
python3 - <<'PY'
import re
from pathlib import Path
root=Path('.')
php=(root/'backend/public/index.php').read_text()
routes=[re.compile('^'+p+'$') for _,p in re.findall(r"matchRoute\(\$method,\$path,'(?:GET|POST|PUT|PATCH|DELETE)','([^']+)'",php)] if False else []
# Extract backend patterns without depending on HTTP method for this source-level existence check.
patterns=[re.compile('^'+p+'$') for p in re.findall(r"matchRoute\(\$method,\$path,'(?:GET|POST|PUT|PATCH|DELETE)','([^']+)'",php)]
missing=[]; count=0
for f in (root/'frontend/src').rglob('*'):
    if f.suffix not in {'.js','.jsx'}: continue
    text=f.read_text()
    for m in re.finditer(r"api\(\s*([`'\"])(.+?)\1",text,re.S):
        template=m.group(2); count+=1
        path='/api'+re.sub(r'\$\{[^}]+\}','123',template)
        if not any(rx.match(path) for rx in patterns): missing.append((str(f),template,path))
if missing:
    for x in missing: print('Missing backend route:',x)
    raise SystemExit(1)
print(f'PASS: {count} frontend API references map to backend route patterns')
PY

echo '[4/9] Objective answer comparison'
php -r 'require "backend/src/Assessment.php"; $m=new ReflectionMethod("Assessment","answersEqual"); $cases=[["single_choice","A","A",true],["single_choice","A","B",false],["multiple_choice",["C","A"],["A","C"],true],["multiple_choice",["A"],["A","C"],false],["true_false","true","true",true],["numeric","60",60,true],["numeric","60.1",60,false]]; foreach($cases as [$t,$g,$c,$want]) if($m->invoke(null,$t,$g,$c)!==$want) exit(1); echo "PASS: objective comparisons\n";'

echo '[5/9] Random shuffle primitive'
php -r 'require "backend/src/Assessment.php"; $m=new ReflectionMethod("Assessment","secureShuffle"); $base=[1,2,3,4,5,6]; $seen=[]; for($i=0;$i<20;$i++){ $x=$base; $args=[&$x]; $m->invokeArgs(null,$args); $sorted=$x; sort($sorted); if($sorted!==$base) exit(1); $seen[implode(",",$x)]=1;} if(count($seen)<2) exit(1); echo "PASS: ".count($seen)." distinct valid permutations\n";'

echo '[6/9] Candidate-safe question delivery / snapshot scoring'
grep -q 'FROM assignment_questions aq JOIN questions q' backend/src/Assessment.php
grep -q 'SUM(q.max_marks).*assignment_questions' backend/src/Assessment.php
if sed -n '/private static function sectionQuestions/,/private static function advanceExpired/p' backend/src/Assessment.php | grep -q 'correct_answer_json'; then echo 'FAIL: candidate question response includes correct answers'; exit 1; fi
grep -q 'candidateSafeMeta' backend/src/Assessment.php
safe_block="$(sed -n '/private static function candidateSafeMeta/,/private static function advanceExpired/p' backend/src/Assessment.php)"
if echo "$safe_block" | grep -E "'reference_answer'|'rubric'|'test_cases'"; then echo 'FAIL: evaluator-only metadata is whitelisted to candidates'; exit 1; fi
echo 'PASS: assignment snapshot drives delivery/scoring; answer keys and evaluator-only metadata excluded from candidate session'

echo '[7/9] Super Admin question bank + modal/overflow hardening'
grep -q 'path="questions" element={<PlatformQuestionBank' frontend/src/App.jsx
grep -q '/api/platform/questions' backend/public/index.php
if grep -R -E 'window\.(prompt|confirm)' frontend/src --include='*.jsx' --include='*.js'; then echo 'FAIL: native popup remains'; exit 1; fi
grep -q 'z-index:1000' frontend/src/styles.css
grep -q 'max-height:calc(100vh - 36px)' frontend/src/styles.css
grep -q 'max-height:calc(100dvh - 16px)' frontend/src/styles.css
grep -q 'overflow:auto' frontend/src/styles.css
echo 'PASS: platform question bank and controlled responsive modal layer'

echo '[8/9] Dashboard / role least-privilege consistency'
grep -q 'Available Questions' frontend/src/pages/AdminDashboard.jsx
grep -q 'company_id=? OR company_id IS NULL' backend/public/index.php
grep -q "\$canEvaluate=in_array(\$user\['role'\],\['company_admin','assessment_manager','examiner'\],true)" backend/public/index.php
grep -q "const canCreate=\['company_admin','assessment_manager'\]" frontend/src/pages/Categories.jsx
echo 'PASS: dashboard count matches usable bank; recruiter evaluator keys are redacted; category actions match backend roles'

echo '[9/9] Seed coverage / requested categories / randomized demo paper'
for term in "Reasoning" "Quantitative Aptitude" "English Reading" "English Writing" "English Speaking" "Coding" "QP-RANDOM-001"; do grep -q "$term" backend/database/seed.php || { echo "FAIL: missing seed $term"; exit 1; }; done
grep -q "'reasoning','Reasoning',12,'random',3,1" backend/database/seed.php
grep -q "'quantitative-aptitude','Quantitative Aptitude',15,'random',3,1" backend/database/seed.php
echo 'PASS: requested categories, answer examples, and randomized demo sections are seeded'

echo 'ALL SOURCE-LEVEL CHECKS PASSED'
