#!/usr/bin/env python3
"""Static implementation evidence for the 18 P0 QA blockers.

This script deliberately does NOT call a result a runtime PASS. It verifies that
required implementation paths exist in the source tree and that Python source
compiles. Runtime acceptance must still be executed against Django/PostgreSQL and
FO-M1 where applicable.
"""
from pathlib import Path
import compileall, sys

ROOT = Path(__file__).resolve().parents[1]
BACKEND = ROOT / "backend"

def has(path, *needles):
    text = (BACKEND / path).read_text(encoding="utf-8", errors="replace")
    return all(n in text for n in needles)

checks = {
    "QA-002": has("apps/attendance/services.py", "def ingest_punch", "sync_attendance_from_punches", "def sync_attendance_from_punches"),
    "QA-006": has("apps/payroll/services.py", "structure_component_monthly_values", "salary_base_for_period", "PayrollLineItem"),
    "QA-009": has("apps/imports/services.py", "def validate_import_job", "staged_rows", "def confirm_import_job") and has("apps/imports/views.py", "validate_import_job", "confirm_import_job"),
    "QA-018": has("apps/payroll/services.py", "def service_bounds", "def _segment_factor", "employee.joining_date"),
    "QA-019": has("apps/payroll/services.py", "def salary_segments", "active_salary_assignment(employee, current)", "assignment.pk != current_assignment.pk"),
    "QA-020": has("apps/attendance/services.py", "MISSING_DAY", "AttendanceRecord.Status.ABSENT", "missing_workday_is_absent"),
    "QA-021": has("apps/attendance/models.py", "class AttendanceDayLedger", "deduction_fraction", "uq_attendance_day_ledger") and has("apps/payroll/services.py", "attendance_deduction_for_period", "ledger.deduction_fraction"),
    "QA-028": has("apps/attendance/services.py", "Build one authoritative day ledger") and has("apps/payroll/services.py", "AttendanceDayLedger.objects.filter"),
    "QA-029": has("apps/payroll/services.py", "def calculate_exit_period_due", "final_working_day", "already_paid_salary"),
    "QA-030": has("apps/exits/models.py", "final_working_day", "final_working_day_finalized_at") and has("apps/exits/services.py", "def finalize_working_day", "Finalize the employee's Final Working Day"),
    "QA-031": has("apps/loans/services.py", "def settle_employee_loans_via_exit", "ExitLoanSettlement", "loan.status = LoanAccount.Status.CLOSED") and has("apps/exits/services.py", "settle_employee_loans_via_exit"),
    "QA-036": has("apps/payroll/services.py", "assert_attendance_period_finalized", "attendance_period_fingerprint", "older attendance close"),
    "QA-037": has("apps/accounts/models.py", "class UserCompanyAccess") and has("apps/accounts/permissions.py", "def accessible_company_ids", "def scope_queryset_by_company", "def user_can_access_company"),
    "QA-050": has("apps/accounts/admin_utils.py", "class CompanyScopedAdminMixin", "formfield_for_foreignkey") and all(has(p, "CompanyScopedAdminMixin") for p in ["apps/attendance/admin.py","apps/employees/admin.py","apps/exits/admin.py","apps/imports/admin.py","apps/leave/admin.py","apps/loans/admin.py","apps/organization/admin.py","apps/payroll/admin.py","apps/workflow/admin.py"]),
    "QA-062": has("apps/leave/services.py", "if decision == \"APPROVED\"", "reconcile_attendance_day") and has("apps/attendance/services.py", "approved_leave_for_day", "source = \"LEAVE\""),
    "QA-064": has("apps/attendance/services.py", "def finalize_attendance_period", "def reopen_attendance_period", "attendance_period_exceptions", "Finalized attendance cannot be edited") and has("apps/attendance/views.py", "period_finalize", "period_reopen"),
    "QA-079": all(has("apps/reports/views.py", needle) for needle in ["company_id__in=accessible_company_ids(request.user)", "employee__company_id__in=accessible_company_ids(request.user)"]),
    "QA-082": has("apps/organization/models.py", "class CompanyPolicy", "effective_from", "salary_proration_method", "missing_punch_action", "ot_rounding_minutes") and has("apps/organization/views.py", "policy_create", "policy_edit", "immutable") and has("apps/organization/services.py", "def get_effective_policy"),
}

compile_ok = compileall.compile_dir(str(BACKEND), quiet=1)
failed = [qa for qa, ok in checks.items() if not ok]
print(f"Python compileall: {'PASS' if compile_ok else 'FAIL'}")
for qa, ok in checks.items():
    print(f"{qa}: {'STATIC EVIDENCE PASS' if ok else 'STATIC EVIDENCE FAIL'}")
if failed or not compile_ok:
    print("Static verifier failed:", ", ".join(failed) or "compileall")
    sys.exit(1)
print("All 18 P0 items have source-level implementation evidence. Runtime/UAT proof is still required.")
