package store import ( "context" "database/sql" "time" "speech-learning-api/internal/domain" ) const foundationFreshness = 7 * 24 * time.Hour const foundationCooldown = 30 * time.Minute type foundationAttempt struct { BankID string Goal string Status string Score float64 At time.Time } type foundationHistory struct { Attempts map[string][]foundationAttempt Assigned map[string]bool } // Only real, graded evidence can reduce practice. Pending/ungraded latest // answers remain in the history so older good scores cannot silently overrule them. func readFoundationHistory(ctx context.Context, tx *sql.Tx, j domain.CourseJob, now time.Time) (foundationHistory, error) { history := foundationHistory{Attempts: map[string][]foundationAttempt{}, Assigned: map[string]bool{}} rows, err := tx.QueryContext(ctx, `SELECT b.id,b.goal,a.status,COALESCE((a.evaluation->>'score')::float8,-1),a.created_at FROM course_v2_attempts a JOIN course_v2_tasks t ON t.id=a.task_id JOIN course_v2_bank b ON b.id=COALESCE(NULLIF(t.data->>'canonical_task_id',''),t.bank_entry_id) LEFT JOIN course_v2_exams e ON e.id=a.exam_id WHERE a.user_id=$1 AND t.owner_id=$1 AND t.language=$2 AND t.version=$3 AND b.module_id=$4 AND NOT a.demo AND (a.exam_id IS NULL OR (e.status='completed' AND e.user_id=$1 AND e.language=$2 AND e.version=$3)) AND a.created_at >= $5 AND a.created_at <= $6 ORDER BY a.created_at DESC,a.id DESC LIMIT 2000`, j.UserID, j.Language, domain.CourseVersion, j.ModuleID, now.Add(-30*24*time.Hour), now) if err != nil { return history, err } for rows.Next() { var attempt foundationAttempt if err = rows.Scan(&attempt.BankID, &attempt.Goal, &attempt.Status, &attempt.Score, &attempt.At); err != nil { rows.Close() return history, err } history.Attempts[attempt.BankID] = append(history.Attempts[attempt.BankID], attempt) } err = rows.Err() rows.Close() if err != nil { return history, err } // Even an unfinished exam assignment is not a new transfer example. Its hidden // grades are excluded above and must never influence this recommendation. rows, err = tx.QueryContext(ctx, `SELECT DISTINCT COALESCE(NULLIF(data->>'canonical_task_id',''),bank_entry_id) FROM course_v2_tasks WHERE owner_id=$1 AND language=$2 AND version=$3 AND module_id=$4 AND COALESCE(NULLIF(data->>'canonical_task_id',''),bank_entry_id) IS NOT NULL`, j.UserID, j.Language, domain.CourseVersion, j.ModuleID) if err != nil { return history, err } defer rows.Close() for rows.Next() { var id string if err = rows.Scan(&id); err != nil { return history, err } history.Assigned[id] = true } return history, rows.Err() } func (h foundationHistory) recentGood(id string, now time.Time) bool { attempts := h.Attempts[id] if len(attempts) == 0 { return false } last := attempts[0] return last.Status == "graded" && last.Score >= 85 && !last.At.After(now) && now.Sub(last.At) <= foundationFreshness } func (h foundationHistory) reusable(step domain.LearningSequenceStep, now time.Time) bool { if !h.recentGood(step.BankEntryID, now) { return false } attempts := h.Attempts[step.BankEntryID] latest := attempts[0] // Avoid immediate massed repetition of the exact same item. This is a short // cooldown, not a declaration of mastery or another successful attempt. if now.Sub(latest.At) <= foundationCooldown { return true } // Repeated clicks/locale variants on the same day do not establish density. for _, attempt := range attempts[1:] { if attempt.Status != "graded" || attempt.Score < 85 { break } if latest.At.Sub(attempt.At) >= 24*time.Hour { return true } } // Only editorially approved sentence-pattern alternatives support transfer; // a different word meaning/preposition with the same broad goal does not. if step.Phase == "grammar" { good := 1 for _, id := range step.Alternatives { if h.recentGood(id, now) { good++ } } return good >= 3 } return false } // Returns an actual candidate or reuses earlier evidence for this scaffold step. // Listening, reading and all production stages always keep their thematic task. func chooseFoundation(step domain.LearningSequenceStep, candidates []bankCandidate, history foundationHistory, now time.Time) (index int, reuse bool, reason string) { index = -1 byID := map[string]int{} for n, c := range candidates { byID[c.bankEntryID] = n } original, ok := byID[step.BankEntryID] if !ok { return -1, false, "" } if step.Phase != "grammar" && step.Phase != "vocabulary" { return original, false, "foundation" } if !history.recentGood(step.BankEntryID, now) { reason = "foundation" if len(history.Attempts[step.BankEntryID]) > 0 { reason = "refresh" } return original, false, reason } for _, id := range step.Alternatives { if n, available := byID[id]; available && !history.Assigned[id] { return n, false, "transfer" } } if history.reusable(step, now) { return original, true, "recent_practice" } return original, false, "refresh" }