# Coding & Engineering Standards

This document establishes the official coding standards, security requirements, and engineering guidelines for the **TFB Engine** codebase. All future coding agents (including you) MUST strictly adhere to these standards.

---

## 1. Environment & Stack Constraints

Performance patches must follow measure-before-optimize: enable lightweight perf trace briefly, record before/after on identical paths, revert changes without measurable value, keep trace off in production, preserve callback dedupe/authz and never log bodies/secrets. Multi-second sleeps and heavy APM dependencies are forbidden on webhook hot paths.

* **PHP 8.1+:** Standard features of PHP 8.1+ (strict types, readonly properties, typed properties, match expressions, array destructuring) are assumed.
* **Strict Types:** Every PHP file MUST begin with `declare(strict_types=1);` strictly.
* **Zero Runtime Composer Dependencies:** To support basic shared cPanel hosting, no third-party packages or frameworks (such as Laravel, Symfony, etc.) may be added to runtime dependencies.
* **Pure PDO:** All database layers use native PHP PDO with prepared statements. No ORMs (like Eloquent or Doctrine) are allowed.

---

## 2. Directory Layout & Architecture Standards

* **Namespace `Tfb\`:** Mapped via PSR-4 to the `src/` directory.
* **SQL Isolation:** 100% of SQL statements MUST reside within Repository classes in `src/Repositories/*`. Services, controllers, and models must *never* contain raw SQL queries.
* **Dumb Models:** Classes in `src/Models/*` are simple data transfer objects containing typed properties and `fromRow`/`toArray` methods. They hold no business logic or database access queries.
* **Thin Controllers:** Controllers in `src/Controllers/*` only parse incoming updates, check authorization, and delegate immediately to underlying services.

---

## 3. Comment Policy

Comments must be correct, useful, and why/intent-oriented, rather than explaining obvious syntax.

### A. Non-Obvious Business Rules
* Comment any critical non-obvious rules (e.g., unique start/complete counters, dual WinnerSelector thresholds, CTA priority matrix, workspace edit lifecycle, callback idempotency, etc.).
* Document why a specific order or logic is used (e.g., why voice note is sent strictly last).

### B. Obvious Syntax
* **Avoid comment spam:** Do not write comments like `// Increment i` or `// Return true`. Let the code speak for itself where the syntax is obvious.

### C. Language
* **Sourse Code & Developer Docs:** English.
* **User-Facing Product UI:** Persian (Farsi).

---

## 4. Security Standards

* **Prepared Statements:** ALWAYS use prepared statements with placeholders (e.g. `:id`) for every single database read/write. Never concatenate variables into SQL query strings.
* **No Secrets in Logs/Comments:** Never log or print sensitive keys like bot tokens, DB passwords, or webhook secret tokens.
* **Automatic Redaction:** Any variable containing patterns resembling a Telegram Bot Token or keywords like `token`, `password`, `secret`, `auth` is centrally redacted in `Tfb\Logging\Redaction`.
* **Escaping Admin Text (HTML Parse Mode):** Any admin-typed free-text fields embedded into HTML-formatted Telegram messages MUST be escaped via `MessageBuilder::escapeHtml()` to prevent markup parse failures.
* **CSRF Protection:** Any setup or change forms (`secure-setup.php`, `install.php`) must use token constant-time comparison CSRF verification.

---

## 5. Telegram-Specific Hardening

* **Anti-Flood & Rate Limits:** 
  - Never call live Telegram API methods (such as `getChatMember`) in a loop over users.
  - Progress messages during broadcast are throttled (every N items) to stay within Telegram's message-edit limits.
* **Callback Idempotency:** Every callback query must be claimed once via `ProcessedCallbackRepository::tryClaim()` using its `callback_query.id`.
* **Stale Keyboard Mitigation:** Ensure that when a user moves to a new phase, older options/buttons are disabled, edited, or deleted so they cannot be clicked again.

---

## 6. Shared Hosting Compliance

* **Lazy Database Connections:** Database connections are opened lazily upon the first actual query run.
* **Time Budgets:** Heavy loops (such as broadcast pumping) are constrained by a wall-clock time budget to prevent CGI/PHP-FPM worker hangs.
* **File Caching:** Cheap, file-based caching (`SettingsService`) is used to store and read configurations without triggering redundant database reads on every webhook hit.
