#!/usr/bin/env python3
"""Dependency-free structural checks for the DigiKinnect source tree."""
from pathlib import Path
import re
import sys

ROOT = Path(__file__).resolve().parents[1]
required = [
    ".env.example", "README.md", "sql/digikinnect.sql", "public/index.php",
    "public/admin.php", "public/enroll.php", "public/pay.php", "public/webhook.php",
    "app/Auth.php", "app/Csrf.php", "app/PaymentService.php", "app/StripeService.php",
    "app/views/admin/settings.php", "scripts/create_admin.php", "scripts/health_check.php",
    "sql/migrations/2026-10-01_settings_and_logos.sql",
]
errors = []
for item in required:
    if not (ROOT / item).is_file():
        errors.append(f"missing required file: {item}")

schema = (ROOT / "sql/digikinnect.sql").read_text(encoding="utf-8")
tables = set(re.findall(r"CREATE TABLE\s+([a-z_]+)", schema, re.I))
expected_tables = {
    "users", "system_settings", "class_groups", "classes", "payment_plans", "parents", "students",
    "enrollments", "enrollment_installments", "payment_requests", "payments",
    "attendance_sessions", "attendance_records", "communications",
    "communication_recipients", "webhook_events", "audit_logs",
}
missing_tables = expected_tables - tables
if missing_tables:
    errors.append("missing schema tables: " + ", ".join(sorted(missing_tables)))

php_files = list(ROOT.rglob("*.php"))
for php_file in php_files:
    text = php_file.read_text(encoding="utf-8")
    if "<?php" not in text and "<?= " not in text:
        errors.append(f"no PHP opening tag: {php_file.relative_to(ROOT)}")
    if "TODO" in text or "FIXME" in text:
        errors.append(f"unfinished marker in {php_file.relative_to(ROOT)}")

admin_source = (ROOT / "public/admin.php").read_text(encoding="utf-8")
for action in ["save_settings", "save_parent", "save_student", "save_group", "save_class", "save_plan", "save_attendance", "send_communication", "save_user"]:
    if f"$action === '{action}'" not in admin_source:
        errors.append(f"admin action is not routed: {action}")

stripe_source = (ROOT / "app/StripeService.php").read_text(encoding="utf-8")
for marker in ["verifyWebhook", "hash_hmac", "checkout/sessions", "Idempotency-Key"]:
    if marker not in stripe_source:
        errors.append(f"Stripe safety marker missing: {marker}")

if errors:
    for error in errors:
        print(f"ERROR: {error}", file=sys.stderr)
    print(f"Static check failed with {len(errors)} error(s).", file=sys.stderr)
    raise SystemExit(1)
print(f"Static check passed: {len(php_files)} PHP files, {len(tables)} database tables, required workflows present.")
