# Python Function Specs & REST API Contracts

> [← 11 Exercise Schemas](./exercise-schemas.md) | [Data & Functions HTML View](./index.html) | [Docs Home](../README.md)

## Backend Attempt-to-Estimate Data Flow

```mermaid
flowchart TD
    Req["POST /api/v1/exercises/{id}/attempt"] --> Norm["text_normalizer.normalize_text()"]
    Norm --> Grade["grader.grade_exercise() (11 handlers)"]
    Grade -->|"Update"| Attempt["Insert ExerciseAttempt"]
    Grade -->|"Each vocab_id"| SRS["srs_service.record_word_outcome()"]
    Grade -->|"Compute XP"| XP["gamification_service.award_exercise_xp()"]
    Done["POST /api/v1/lessons/{id}/complete"] --> Stars["complete_lesson_rewards() (1-3★ + Stickers)"]
    Done --> Est["score_estimator.recompute_course_estimate()"]
```

## Detailed Python Function Specifications

| Module | Function Signature | Inputs / Logic / Output |
| :--- | :--- | :--- |
| `text_normalizer.py` | `normalize_text(text: str, *, casefold=True, strip_punct=True) -> str` | Unicode `NFC`, trims/collapses whitespace, preserves combining marks |
| `text_normalizer.py` | `compare_answers(submitted: str, expected: str, *, lenient_diacritics=False) -> AnswerMatchResult` | Returns `(is_exact, is_accent_only_diff, normalized_submitted)` for diacritic coaching |
| `text_normalizer.py` | `tokenize_for_tiles(text: str, tokenization_mode: str) -> List[str]` | Splits by `space`, `char` (CJK), or `syllable` (Kana/Hangul) |
| `grader.py` | `grade_exercise(exercise: Exercise, submitted: dict, *, gameplay_mode="playful", strict_accents=False, attempt_number=1) -> GradeOutcome` | Dispatches via `GRADER_REGISTRY` across all 11 types; attaches `explanation` & `evidence_quotes` |
| `placement_engine.py` | `start_placement_session(db: Session, course_id: int, *, max_items=8) -> PlacementStartOut` | Samples up to 8 escalating `A1->C1` / `N5->N1` exercises |
| `placement_engine.py` | `evaluate_placement(db: Session, profile: LearnerProfile, course_id: int, answers: List[PlacementAnswerItem]) -> PlacementResultOut` | Weights tier accuracy, recommends starting unit, marks foundational lessons `"tested_out"` |
| `score_estimator.py` | `recompute_course_estimate(db: Session, profile_id: int, course_id: int) -> UserSkillEstimate` | Aggregates weighted tier accuracy per `skill_focus` → IELTS Band `4.0–9.0`, TOEIC `300–990`, JLPT `N5–N1 %`, TESOL Tier |
| `session_builder.py` | `sanitize_exercise_for_client(db, exercise, language, *, preferred_accent="default", shuffle_seed=None) -> ExerciseOut` | Strips grading answers, shuffles tray deterministically, resolves audio specs |
| `session_builder.py` | `build_lesson_session(db: Session, profile: LearnerProfile, lesson_id: int) -> LessonSessionOut` | Orders exercises, checks unlock status, builds playable session |
| `session_builder.py` | `build_review_session(db: Session, profile: LearnerProfile, course_id: int, limit=8) -> LessonSessionOut` | Pulls due SRS items & synthesizes mixed Brain Boost drills |
| `srs_service.py` | `record_word_outcome(db: Session, profile_id: int, vocab_id: int, is_correct: bool, duration_ms=3000) -> WordMasterySRS` | SM-2 lite: adjusts `ease_factor`, resets `interval_days=1` on miss or `1->3->prev*ef` on pass |
| `gamification_service.py` | `award_exercise_xp(profile: LearnerProfile, is_correct: bool, combo_count: int) -> tuple[int, int]` | Computes streak & combo-boosted XP per attempt |
| `gamification_service.py` | `complete_lesson_rewards(db: Session, profile: LearnerProfile, lesson_id: int, correct_count: int, total_count: int) -> LessonCompleteSummary` | Calculates 1–3★, unlocks next lesson, updates streak, evaluates `Sticker` rules |
| `pack_service.py` | `validate_pack_data(raw_data: dict) -> Tuple[CurriculumPackSchema, PackValidationReport]` | Validates language metadata, Bidi safety, 11-type exercise schemas & tile solvability |
| `pack_service.py` | `import_pack_to_db(db: Session, pack: CurriculumPackSchema) -> ImportStats` | Atomic slug-based upsert for `Language`, `Course`, `VocabularyItem`, `GrammarConcept`, `Unit`, `Lesson`, `Exercise` |

## Page Routes & REST `/api/v1` Endpoints Matrix

| Method & Route | Purpose | Key Payload / Response |
| :--- | :--- | :--- |
| `GET /`, `/learn`, `/placement`, `/lesson/{id}`, `/review`, `/stickers`, `/parent`, `/studio` | Server-rendered HTML pages + `/healthz`, `/favicon.ico` & edge `/docs-portal/` | Jinja2 (local) / Hono SSR HTML (edge) + `ProfileOut` HUD context |
| `POST /api/v1/auth/guest`, `/register`, `/login`, `/logout` | Zero-PII guest start & optional registered account upgrade/auth | `{nickname, avatar_id, course_slug, gameplay_mode}` → Signed Cookie + `ProfileOut` |
| `GET /api/v1/profile/me`, `PATCH /api/v1/profile/preferences` | Fetch or toggle Playful/Exam, Script, Accent, Open Access, SFX | `{gameplay_mode?, script_mode?, preferred_accent?, open_access?, sound_enabled?}` |
| `GET /api/v1/languages` | List languages & tracks (`IELTS`, `TOEIC`, `TESOL`, `JLPT`, `CEFR`) | `{"languages": LanguageOut[], "courses": CourseSummaryOut[]}` |
| `GET /api/v1/courses/{slug}/map` | Load tiered island map (`?tier=&skill=`) | `CourseMapOut` (`unlocked`/`completed`/`locked`) + `SkillEstimateOut` |
| `POST /api/v1/placement/{slug}/start` & `/submit` | Adaptive placement diagnostic sprint | `PlacementStartOut` → `PlacementResultOut` |
| `GET /api/v1/lessons/{id}/session` | Start 11-type lesson session | `LessonSessionOut` |
| `POST /api/v1/exercises/{id}/attempt` | Submit drag-drop answer & get explanation | `AttemptSubmitRequest` → `AttemptResultResponse` |
| `POST /api/v1/lessons/{id}/complete` | Finalize stars, XP, stickers & readiness | `{correct_count, total_count, duration_ms}` → `LessonCompleteSummary` |
| `GET /api/v1/review/brain-boost` | Dynamic SM-2 adaptive review session | `LessonSessionOut` |
| `GET /api/v1/stickers` | Sticker album unlocked & locked badges | `StickerAlbumOut` |
| `POST /api/v1/parent/verify-pin`, `GET /api/v1/parent/analytics`, `POST /api/v1/parent/reset-progress` | Parent PIN guard, skill analytics & progress reset | `ParentAnalyticsOut` |
| `POST /api/v1/studio/packs/validate`, `/import`, `GET /api/v1/studio/courses/{slug}/export` | Validate, import, or export YAML/JSON pack | `PackValidationReport` / `ImportStats` / YAML/JSON |

## Edge TypeScript Worker Module Mapping (`worker/src/lib/`)

| Python Module (`app/`) | Edge Cloudflare Worker Module (`worker/src/lib/`) | Parity Role |
| :--- | :--- | :--- |
| `app/core/security.py` | `worker/src/lib/security.ts` | `HS256` JWT + `100k` PBKDF2-SHA256 via Web Crypto |
| `app/exercises/text_normalizer.py` | `worker/src/lib/text_normalizer.ts` | Unicode NFC + diacritics (incl. Polish `ł`) + tokenizers |
| `app/exercises/grader.py` | `worker/src/lib/grader.ts` | All 11 `GRADER_REGISTRY` handlers |
| `app/exercises/{session_builder,placement_engine,score_estimator}.py` | `worker/src/lib/{session_builder,placement_engine,score_estimator}.ts` | Sanitized tray shuffle, placement & exam estimators |
| `app/services/{srs,gamification,auth,curriculum,pack}_service.py` | `worker/src/lib/{srs_gamification,profile,curriculum,pack_service}.ts` | D1 parameterized persistence & Studio YAML import/export |

## Changelog

| Version | Date | Summary of Changes |
| :--- | :--- | :--- |
| **v1.2.0** | 2026-11-22 | Added Python ↔ TypeScript Edge Worker parity mapping table (`worker/src/lib/*`) and Cloudflare Edge `/docs-portal/` + `GET /healthz` (`runtime: cloudflare-worker-d1`). |
| **v1.1.0** | 2026-11-15 | Synchronized every Python function signature (`grade_exercise`, `complete_lesson_rewards`, `award_exercise_xp`, `sanitize_exercise_for_client`) and added all 8 HTML + 21 REST routes (`/auth/*`, `/profile/me`, `/stickers`, `/parent/*`, `/studio/courses/{slug}/export`, `/review`, `/healthz`). |
| **v1.0.0** | 2026-11-15 | Initial Python functions & REST API specification. |

