File size: 55,396 Bytes
c02657c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
"""OPUS-synth: programmatically generated, *verified* training examples (English + Turkish).

Every example is produced by code that also computes the ground-truth answer, so the
final answer of every response is correct by construction. Responses show their work
step by step; each arithmetic line is re-checked by `check_arithmetic` before an
example is accepted. Code tasks are executed against unit tests in a subprocess.

Families
    word_problem   multi-step arithmetic word problems (shopping, speed, discounts, ...)
    arithmetic     exact fraction / order-of-operations evaluation
    algebra        linear equations and 2x2 linear systems
    number_theory  gcd/lcm (Euclid), prime factorisation, base conversion
    dates          day differences, weekdays, adding days
    strings        letter counting, reversal, sorting, word counts
    logic          ordering puzzles with a unique solution (verified by brute force)
    code           Python functions verified by unit tests
    json           structured extraction into JSON
    unanswerable   problems with missing information -> the model should say so
    units          unit conversions
"""
import datetime as dt
import itertools
import json
import math
import random
import re
import subprocess
import sys
import tempfile
from fractions import Fraction

from .text import stable_id

# --------------------------------------------------------------------------- helpers

NAMES_EN = ["Alice", "Ben", "Chloe", "David", "Emma", "Farid", "Grace", "Hiro", "Isla", "Jonas",
            "Kemal", "Lena", "Mateo", "Nora", "Omar", "Priya", "Quinn", "Rosa", "Sam", "Tara"]
NAMES_TR = ["Ayşe", "Mehmet", "Zeynep", "Can", "Elif", "Burak", "Deniz", "Emre", "Selin", "Mert",
            "Ece", "Kerem", "Defne", "Arda", "İpek", "Onur", "Derya", "Yusuf", "Ceren", "Barış"]


def fmt(x):
    """Format a Fraction/int/float for display (integers without decimals, otherwise exact)."""
    if isinstance(x, Fraction):
        if x.denominator == 1:
            return str(x.numerator)
        if (x * 100).denominator == 1:
            return f"{float(x):.2f}".rstrip("0").rstrip(".")
        return f"{x.numerator}/{x.denominator}"
    if isinstance(x, float):
        return f"{x:.2f}".rstrip("0").rstrip(".")
    return str(x)


_TR_VOWELS = "aıoueiöüAIOUEİÖÜ"
_TR_HARD = "fstkçşhpFSTKÇŞHP"


def tr_ek(word, kind):
    """Attach a Turkish case suffix with an apostrophe (proper nouns), respecting vowel harmony.

    kind: 'gen' (-in), 'abl' (-den), 'loc' (-de).
    """
    w = str(word)
    last_v = next((c for c in reversed(w.lower()) if c in "aıoueiöü"), "e")
    ends_vowel = w[-1] in _TR_VOWELS
    hard = w[-1] in _TR_HARD
    if kind == "gen":
        v = {"a": "ı", "ı": "ı", "o": "u", "u": "u", "e": "i", "i": "i", "ö": "ü", "ü": "ü"}[last_v]
        return f"{w}'{'n' if ends_vowel else ''}{v}n"
    v = "a" if last_v in "aıou" else "e"
    d = "t" if hard else "d"
    return f"{w}'{d}{v}" + ("n" if kind == "abl" else "")


def money(x, lang):
    s = f"{float(x):.2f}"
    return f"${s}" if lang == "en" else f"{s.replace('.', ',')} TL"


_ARITH = re.compile(r"(?<![\w.,/])(\d+(?:\.\d+)?(?:\s*[+\-×÷*/]\s*\d+(?:\.\d+)?)+)\s*=\s*(\d+(?:\.\d+)?)(?![\w/])")


def check_arithmetic(text):
    """Re-evaluate every explicit `a op b op c = d` line in a response. Returns #errors."""
    errors = 0
    for m in _ARITH.finditer(text):
        expr = m.group(1).replace("×", "*").replace("÷", "/")
        try:
            toks = re.findall(r"\d+(?:\.\d+)?|[+\-*/]", expr)
            val = _eval_tokens(toks)
            if abs(val - Fraction(m.group(2))) > Fraction(1, 100):
                errors += 1
        except (ZeroDivisionError, ValueError, IndexError):
            errors += 1
    return errors


def _eval_tokens(toks):
    # shunting-yard for + - * / on Fractions
    prec = {"+": 1, "-": 1, "*": 2, "/": 2}
    out, ops = [], []
    for t in toks:
        if t in prec:
            while ops and prec[ops[-1]] >= prec[t]:
                out.append(ops.pop())
            ops.append(t)
        else:
            out.append(Fraction(t))
    out.extend(reversed(ops))
    st = []
    for t in out:
        if isinstance(t, Fraction):
            st.append(t)
        else:
            b, a = st.pop(), st.pop()
            st.append(a + b if t == "+" else a - b if t == "-" else a * b if t == "*" else a / b)
    if len(st) != 1:
        raise ValueError
    return st[0]


def example(family, lang, prompt, response, answer, rng_seed, difficulty=1, extra=None):
    return {
        "id": "synth-" + stable_id(family, lang, prompt),
        "family": family,
        "language": lang,
        "difficulty": difficulty,
        "prompt": prompt,
        "response": response,
        "answer": str(answer),
        "seed": rng_seed,
        **(extra or {}),
    }


def final_line(ans, lang):
    return f"\n\n**Answer:** {ans}" if lang == "en" else f"\n\n**Cevap:** {ans}"


# --------------------------------------------------------------------------- word problems

def wp_shopping(r, lang):
    n = r.choice(NAMES_EN if lang == "en" else NAMES_TR)
    items_en = [("notebooks", "pens"), ("apples", "oranges"), ("tickets", "snacks"), ("books", "bookmarks")]
    items_tr = [("defter", "kalem"), ("elma", "portakal"), ("bilet", "atıştırmalık"), ("kitap", "ayraç")]
    a_name, b_name = r.choice(items_en if lang == "en" else items_tr)
    a, b = r.randint(2, 9), r.randint(2, 12)
    pa = Fraction(r.randint(50, 1500), 100)
    pb = Fraction(r.randint(25, 600), 100)
    total = a * pa + b * pb
    bill = next(x for x in (10, 20, 50, 100, 200, 500) if x >= total)
    change = bill - total
    if lang == "en":
        p = (f"{n} buys {a} {a_name} at {money(pa, lang)} each and {b} {b_name} at {money(pb, lang)} each. "
             f"{n} pays with a {money(bill, lang)} bill. How much change does {n} receive?")
        s = (f"Cost of the {a_name}: {a} × {fmt(pa)} = {fmt(a * pa)}\n"
             f"Cost of the {b_name}: {b} × {fmt(pb)} = {fmt(b * pb)}\n"
             f"Total cost: {fmt(a * pa)} + {fmt(b * pb)} = {fmt(total)}\n"
             f"Change: {bill} - {fmt(total)} = {fmt(change)}\n\n"
             f"{n} receives {money(change, lang)} in change.")
    else:
        p = (f"{n}, tanesi {money(pa, lang)} olan {a} {a_name} ve tanesi {money(pb, lang)} olan {b} {b_name} alıyor. "
             f"{n} ödemeyi {money(bill, lang)} ile yapıyor. {n} ne kadar para üstü alır?")
        s = (f"{a_name.capitalize()} tutarı: {a} × {fmt(pa)} = {fmt(a * pa)}\n"
             f"{b_name.capitalize()} tutarı: {b} × {fmt(pb)} = {fmt(b * pb)}\n"
             f"Toplam tutar: {fmt(a * pa)} + {fmt(b * pb)} = {fmt(total)}\n"
             f"Para üstü: {bill} - {fmt(total)} = {fmt(change)}\n\n"
             f"{n} {money(change, lang)} para üstü alır.")
    return p, s, fmt(change), 2


def wp_speed(r, lang):
    n = r.choice(NAMES_EN if lang == "en" else NAMES_TR)
    v1, v2 = r.choice([40, 45, 50, 60, 72, 75, 80, 90]), r.choice([30, 40, 48, 60, 64, 80, 96, 100])
    t1, t2 = Fraction(r.randint(1, 8), 4), Fraction(r.randint(1, 8), 4)
    d1, d2 = v1 * t1, v2 * t2
    total_t = t1 + t2
    avg = (d1 + d2) / total_t
    if lang == "en":
        p = (f"{n} drives {fmt(d1)} km at {v1} km/h and then {fmt(d2)} km at {v2} km/h. "
             f"What is the average speed for the whole trip in km/h?")
        s = (f"Time for the first part: {fmt(d1)} ÷ {v1} = {fmt(t1)} hours\n"
             f"Time for the second part: {fmt(d2)} ÷ {v2} = {fmt(t2)} hours\n"
             f"Total distance: {fmt(d1)} + {fmt(d2)} = {fmt(d1 + d2)} km\n"
             f"Total time: {fmt(t1)} + {fmt(t2)} = {fmt(total_t)} hours\n"
             f"Average speed = total distance ÷ total time = {fmt(d1 + d2)} ÷ {fmt(total_t)} = {fmt(avg)} km/h\n\n"
             f"Note that the average speed is not simply the mean of {v1} and {v2}, because the two parts take different amounts of time.")
    else:
        p = (f"{n} önce {fmt(d1)} km yolu {v1} km/sa hızla, ardından {fmt(d2)} km yolu {v2} km/sa hızla gidiyor. "
             f"Tüm yolculuğun ortalama hızı kaç km/sa'dir?")
        s = (f"Birinci bölümün süresi: {fmt(d1)} ÷ {v1} = {fmt(t1)} saat\n"
             f"İkinci bölümün süresi: {fmt(d2)} ÷ {v2} = {fmt(t2)} saat\n"
             f"Toplam yol: {fmt(d1)} + {fmt(d2)} = {fmt(d1 + d2)} km\n"
             f"Toplam süre: {fmt(t1)} + {fmt(t2)} = {fmt(total_t)} saat\n"
             f"Ortalama hız = toplam yol ÷ toplam süre = {fmt(d1 + d2)} ÷ {fmt(total_t)} = {fmt(avg)} km/sa\n\n"
             f"Ortalama hız, {v1} ile {v2} değerlerinin basit ortalaması değildir; çünkü iki bölüm farklı sürelerde gidilmiştir.")
    return p, s, fmt(avg), 3


def wp_discount(r, lang):
    price = r.randint(20, 900)
    disc = r.choice([5, 10, 15, 20, 25, 30, 40, 50])
    tax = r.choice([8, 10, 18, 20])
    after = Fraction(price) * (100 - disc) / 100
    final = after * (100 + tax) / 100
    if lang == "en":
        p = (f"A jacket costs {money(price, lang)}. It is discounted by {disc}%, and then a {tax}% sales tax is added "
             f"to the discounted price. What is the final price?")
        s = (f"Discount amount: {price} × {disc} ÷ 100 = {fmt(Fraction(price * disc, 100))}\n"
             f"Discounted price: {price} - {fmt(Fraction(price * disc, 100))} = {fmt(after)}\n"
             f"Tax: {fmt(after)} × {tax} ÷ 100 = {fmt(after * tax / 100)}\n"
             f"Final price: {fmt(after)} + {fmt(after * tax / 100)} = {fmt(final)}\n\n"
             f"The final price is {money(final, lang)}.")
    else:
        p = (f"Bir ceketin fiyatı {money(price, lang)}. Ceket %{disc} indirimli satılıyor ve indirimli fiyata %{tax} KDV ekleniyor. "
             f"Son fiyat nedir?")
        s = (f"İndirim tutarı: {price} × {disc} ÷ 100 = {fmt(Fraction(price * disc, 100))}\n"
             f"İndirimli fiyat: {price} - {fmt(Fraction(price * disc, 100))} = {fmt(after)}\n"
             f"KDV: {fmt(after)} × {tax} ÷ 100 = {fmt(after * tax / 100)}\n"
             f"Son fiyat: {fmt(after)} + {fmt(after * tax / 100)} = {fmt(final)}\n\n"
             f"Son fiyat {money(final, lang)} olur.")
    return p, s, f"{float(final):.2f}", 2


def wp_work(r, lang):
    a, b = r.sample([2, 3, 4, 5, 6, 8, 10, 12, 15], 2)
    together = Fraction(a * b, a + b)
    minutes = together * 60
    if lang == "en":
        p = (f"One pipe can fill a tank in {a} hours and another pipe can fill the same tank in {b} hours. "
             f"If both pipes are opened together, how many minutes will it take to fill the tank?")
        s = (f"Rate of the first pipe: 1/{a} of the tank per hour.\n"
             f"Rate of the second pipe: 1/{b} of the tank per hour.\n"
             f"Combined rate: 1/{a} + 1/{b} = {b + a}/{a * b} of the tank per hour.\n"
             f"Time = 1 ÷ ({a + b}/{a * b}) = {a * b}/{a + b} hours = {fmt(together)} hours.\n"
             f"In minutes: {fmt(together)} × 60 = {fmt(minutes)}")
        ans = fmt(minutes)
        s += f"\n\nThe tank is full after {ans} minutes."
    else:
        p = (f"Bir musluk bir depoyu {a} saatte, başka bir musluk aynı depoyu {b} saatte dolduruyor. "
             f"İki musluk birlikte açılırsa depo kaç dakikada dolar?")
        s = (f"Birinci musluğun hızı: saatte deponun 1/{a}'i.\n"
             f"İkinci musluğun hızı: saatte deponun 1/{b}'i.\n"
             f"Birlikte hız: 1/{a} + 1/{b} = {a + b}/{a * b} (depo/saat).\n"
             f"Süre = 1 ÷ ({a + b}/{a * b}) = {a * b}/{a + b} saat = {fmt(together)} saat.\n"
             f"Dakika olarak: {fmt(together)} × 60 = {fmt(minutes)}")
        ans = fmt(minutes)
        s += f"\n\nDepo {ans} dakikada dolar."
    return p, s, ans, 3


def wp_savings(r, lang):
    n = r.choice(NAMES_EN if lang == "en" else NAMES_TR)
    start = r.randint(0, 200)
    weekly = r.randint(5, 60)
    goal = start + weekly * r.randint(3, 40) - r.randint(0, weekly - 1)
    need = goal - start
    weeks = math.ceil(need / weekly)
    if lang == "en":
        p = (f"{n} has {money(start, lang)} saved and adds {money(weekly, lang)} every week. "
             f"After how many full weeks will {n} have at least {money(goal, lang)}?")
        s = (f"Amount still needed: {goal} - {start} = {need}\n"
             f"Weeks needed: {need} ÷ {weekly} ≈ {need / weekly:.2f}, so we round up to {weeks} weeks.\n"
             f"Check: {start} + {weekly} × {weeks} = {start + weekly * weeks}, which is at least {goal}, "
             f"while after {weeks - 1} weeks {n} would have {start + weekly * (weeks - 1)}.")
    else:
        p = (f"{tr_ek(n, 'gen')} {money(start, lang)} birikimi var ve her hafta {money(weekly, lang)} ekliyor. "
             f"Kaç tam hafta sonra {tr_ek(n, 'gen')} en az {money(goal, lang)} parası olur?")
        s = (f"Eksik tutar: {goal} - {start} = {need}\n"
             f"Gereken hafta: {need} ÷ {weekly} ≈ {need / weekly:.2f}; yukarı yuvarlarız: {weeks} hafta.\n"
             f"Kontrol: {start} + {weekly} × {weeks} = {start + weekly * weeks}, bu değer {goal} değerinden küçük değil; "
             f"{weeks - 1} hafta sonra ise {start + weekly * (weeks - 1)} olurdu.")
    return p, s, weeks, 2


def wp_ages(r, lang):
    child = r.randint(4, 20)
    k = r.randint(2, 4)
    years = r.randint(2, 15)
    parent_future = k * (child + years)
    parent = parent_future - years
    if parent - child < 16:
        return wp_ages(r, lang)
    if lang == "en":
        p = (f"A parent is {parent} years old. In {years} years, the parent will be {k} times as old as their child "
             f"will be then. How old is the child now?")
        s = (f"Let the child's current age be x.\n"
             f"In {years} years: parent = {parent} + {years} = {parent + years}, child = x + {years}.\n"
             f"Equation: {parent + years} = {k}(x + {years})\n"
             f"x + {years} = {parent + years} ÷ {k} = {child + years}\n"
             f"x = {child + years} - {years} = {child}")
    else:
        p = (f"Bir ebeveyn {parent} yaşında. {years} yıl sonra ebeveynin yaşı, çocuğunun o zamanki yaşının {k} katı olacak. "
             f"Çocuk şimdi kaç yaşında?")
        s = (f"Çocuğun bugünkü yaşına x diyelim.\n"
             f"{years} yıl sonra: ebeveyn = {parent} + {years} = {parent + years}, çocuk = x + {years}.\n"
             f"Denklem: {parent + years} = {k}(x + {years})\n"
             f"x + {years} = {parent + years} ÷ {k} = {child + years}\n"
             f"x = {child + years} - {years} = {child}")
    return p, s, child, 3


def wp_recipe(r, lang):
    base, target = r.choice([(4, 6), (4, 10), (6, 9), (2, 5), (8, 12), (3, 7)])
    flour = r.choice([200, 250, 300, 360, 400, 450])
    sugar = r.choice([80, 100, 120, 150, 180])
    f2, s2 = Fraction(flour * target, base), Fraction(sugar * target, base)
    if lang == "en":
        p = (f"A recipe for {base} people uses {flour} g of flour and {sugar} g of sugar. "
             f"How many grams of flour and sugar are needed for {target} people?")
        s = (f"Scale factor: {target} ÷ {base} = {fmt(Fraction(target, base))}\n"
             f"Flour: {flour} × {target} ÷ {base} = {fmt(f2)} g\n"
             f"Sugar: {sugar} × {target} ÷ {base} = {fmt(s2)} g")
    else:
        p = (f"{base} kişilik bir tarifte {flour} g un ve {sugar} g şeker kullanılıyor. "
             f"{target} kişi için kaç gram un ve şeker gerekir?")
        s = (f"Ölçek katsayısı: {target} ÷ {base} = {fmt(Fraction(target, base))}\n"
             f"Un: {flour} × {target} ÷ {base} = {fmt(f2)} g\n"
             f"Şeker: {sugar} × {target} ÷ {base} = {fmt(s2)} g")
    return p, s, f"{fmt(f2)}, {fmt(s2)}", 1


def wp_interest(r, lang):
    principal = r.choice([1000, 2000, 2500, 5000, 8000, 10000])
    rate = r.choice([2, 3, 4, 5, 6, 8, 10])
    years = r.randint(2, 4)
    lines, bal = [], Fraction(principal)
    for y in range(1, years + 1):
        new = bal * (100 + rate) / 100
        lines.append((y, bal, new))
        bal = new
    if lang == "en":
        p = (f"You deposit {money(principal, lang)} in an account that pays {rate}% interest per year, compounded annually. "
             f"How much is in the account after {years} years? Round to the nearest cent.")
        s = "\n".join(f"End of year {y}: {float(b):.2f} × {1 + rate / 100:.2f} = {float(n):.2f}" for y, b, n in lines)
        s += f"\n\nEquivalently, {principal} × {1 + rate / 100:.2f}^{years} = {float(bal):.2f}. The balance is {money(bal, lang)}."
    else:
        p = (f"Yıllık %{rate} bileşik faiz veren bir hesaba {money(principal, lang)} yatırıyorsunuz. "
             f"{years} yıl sonra hesapta ne kadar para olur? Kuruşa yuvarlayın.")
        s = "\n".join(f"{y}. yıl sonu: {float(b):.2f} × {1 + rate / 100:.2f} = {float(n):.2f}" for y, b, n in lines)
        s += f"\n\nKısaca: {principal} × {1 + rate / 100:.2f}^{years} = {float(bal):.2f}. Bakiye {money(bal, lang)} olur."
    return p, s, f"{float(bal):.2f}", 2


WORD_PROBLEMS = [wp_shopping, wp_speed, wp_discount, wp_work, wp_savings, wp_ages, wp_recipe, wp_interest]


def gen_word_problem(r, lang):
    fn = r.choice(WORD_PROBLEMS)
    p, s, ans, d = fn(r, lang)
    return "word_problem/" + fn.__name__[3:], p, s + final_line(ans, lang), ans, d


# --------------------------------------------------------------------------- arithmetic & algebra

def gen_arithmetic(r, lang):
    a, b, c, d = (Fraction(r.randint(1, 12), r.choice([1, 2, 3, 4, 5, 6])) for _ in range(4))
    op1, op2 = r.choice("+-"), r.choice("×÷")
    inner = a + b if op1 == "+" else a - b
    res = inner * c / d if op2 == "×" else inner / c * d
    expr = f"({fmt(a)} {op1} {fmt(b)}) {op2} {fmt(c)} {'÷' if op2 == '×' else '×'} {fmt(d)}"
    second = inner * c if op2 == "×" else inner / c
    third_op = "÷" if op2 == "×" else "×"
    if lang == "en":
        p = f"Compute exactly and give the answer as a fraction in lowest terms if it is not an integer: {expr}"
        s = (f"Step 1 (parentheses): {fmt(a)} {op1} {fmt(b)} = {fmt(inner)}\n"
             f"Step 2 (left to right): {fmt(inner)} {op2} {fmt(c)} = {fmt(second)}\n"
             f"Step 3: {fmt(second)} {third_op} {fmt(d)} = {fmt(res)}")
    else:
        p = f"Tam olarak hesaplayın; sonuç tam sayı değilse en sade kesir olarak verin: {expr}"
        s = (f"Adım 1 (parantez): {fmt(a)} {op1} {fmt(b)} = {fmt(inner)}\n"
             f"Adım 2 (soldan sağa): {fmt(inner)} {op2} {fmt(c)} = {fmt(second)}\n"
             f"Adım 3: {fmt(second)} {third_op} {fmt(d)} = {fmt(res)}")
    ans = f"{res.numerator}/{res.denominator}" if res.denominator != 1 else str(res.numerator)
    return "arithmetic/fractions", p, s + final_line(ans, lang), ans, 2


def par(v):
    return f"({v})" if v < 0 else str(v)


def term(coef, var):
    return var if coef == 1 else f"-{var}" if coef == -1 else f"{coef}{var}"


def lin(a, b):
    tb = term(abs(b), "y")
    return f"{term(a, 'x')} {'+' if b > 0 else '-'} {tb}"


def gen_algebra(r, lang):
    if r.random() < 0.5:
        x = r.randint(-12, 12)
        a, c = r.sample([v for v in range(-9, 10) if v], 2)
        b = r.randint(-30, 30)
        d = a * x + b - c * x
        sgn = lambda v: f"+ {v}" if v >= 0 else f"- {-v}"
        eq = f"{term(a, 'x')} {sgn(b)} = {term(c, 'x')} {sgn(d)}"
        if lang == "en":
            p = f"Solve for x: {eq}"
            s = (f"Move the x terms to the left and the constants to the right:\n"
                 f"{term(a, 'x')} - ({term(c, 'x')}) = {d} - ({b})\n"
                 f"{term(a - c, 'x')} = {d - b}\n"
                 f"x = {d - b} / {a - c} = {x}\n\n"
                 f"Check: left side {a}·{par(x)} {sgn(b)} = {a * x + b}; right side {c}·{par(x)} {sgn(d)} = {c * x + d}. ✓")
        else:
            p = f"x'i bulun: {eq}"
            s = (f"x'li terimleri sola, sabitleri sağa toplayalım:\n"
                 f"{term(a, 'x')} - ({term(c, 'x')}) = {d} - ({b})\n"
                 f"{term(a - c, 'x')} = {d - b}\n"
                 f"x = {d - b} / {a - c} = {x}\n\n"
                 f"Kontrol: sol taraf {a}·{par(x)} {sgn(b)} = {a * x + b}; sağ taraf {c}·{par(x)} {sgn(d)} = {c * x + d}. ✓")
        return "algebra/linear", p, s + final_line(f"x = {x}", lang), str(x), 2
    x, y = r.randint(-9, 9), r.randint(-9, 9)
    while True:
        a, b, c, d = (r.choice([v for v in range(-6, 7) if v]) for _ in range(4))
        if a * d - b * c:
            break
    e, f = a * x + b * y, c * x + d * y
    det = a * d - b * c
    if lang == "en":
        p = f"Solve the system:\n{lin(a, b)} = {e}\n{lin(c, d)} = {f}"
        s = (f"Use Cramer's rule. Determinant D = ({a})({d}) - ({b})({c}) = {det}.\n"
             f"Dx = ({e})({d}) - ({b})({f}) = {e * d - b * f}, so x = {e * d - b * f} / {det} = {x}.\n"
             f"Dy = ({a})({f}) - ({e})({c}) = {a * f - e * c}, so y = {a * f - e * c} / {det} = {y}.\n\n"
             f"Check: {a}·{par(x)} + {par(b)}·{par(y)} = {e} ✓ and {c}·{par(x)} + {par(d)}·{par(y)} = {f} ✓")
    else:
        p = f"Denklem sistemini çözün:\n{lin(a, b)} = {e}\n{lin(c, d)} = {f}"
        s = (f"Cramer kuralını kullanalım. Determinant D = ({a})({d}) - ({b})({c}) = {det}.\n"
             f"Dx = ({e})({d}) - ({b})({f}) = {e * d - b * f}, dolayısıyla x = {e * d - b * f} / {det} = {x}.\n"
             f"Dy = ({a})({f}) - ({e})({c}) = {a * f - e * c}, dolayısıyla y = {a * f - e * c} / {det} = {y}.\n\n"
             f"Kontrol: {a}·{par(x)} + {par(b)}·{par(y)} = {e} ✓ ve {c}·{par(x)} + {par(d)}·{par(y)} = {f} ✓")
    return "algebra/system2x2", p, s + final_line(f"x = {x}, y = {y}", lang), f"{x}, {y}", 3


def gen_number_theory(r, lang):
    kind = r.choice(["gcd", "factor", "base"])
    if kind == "gcd":
        g = r.randint(2, 40)
        a, b = g * r.randint(2, 60), g * r.randint(2, 60)
        a, b = max(a, b), min(a, b)
        steps, x, y = [], a, b
        while y:
            steps.append(f"{x} = {x // y} × {y} + {x % y}")
            x, y = y, x % y
        lcm = a * b // x
        head = "Euclid's algorithm:" if lang == "en" else "Öklid algoritması:"
        tail = (f"The last non-zero remainder is {x}, so gcd({a}, {b}) = {x}.\nlcm({a}, {b}) = {a} × {b} ÷ {x} = {lcm}."
                if lang == "en" else
                f"Sıfır olmayan son kalan {x}; dolayısıyla EBOB({a}, {b}) = {x}.\nEKOK({a}, {b}) = {a} × {b} ÷ {x} = {lcm}.")
        p = (f"Find the greatest common divisor and least common multiple of {a} and {b}." if lang == "en"
             else f"{a} ve {b} sayılarının EBOB ve EKOK'unu bulun.")
        ans = f"{x}, {lcm}"
        return "number_theory/gcd_lcm", p, head + "\n" + "\n".join(steps) + "\n" + tail + final_line(ans, lang), ans, 2
    if kind == "factor":
        primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
        fs = sorted(r.choice(primes) for _ in range(r.randint(2, 6)))
        n = math.prod(fs)
        steps, m = [], n
        for pr in fs:
            steps.append(f"{m} ÷ {pr} = {m // pr}")
            m //= pr
        counts = {pr: fs.count(pr) for pr in sorted(set(fs))}
        ans = " × ".join(f"{pr}^{c}" if c > 1 else str(pr) for pr, c in counts.items())
        p = (f"Find the prime factorization of {n}." if lang == "en" else f"{n} sayısını asal çarpanlarına ayırın.")
        head = "Divide repeatedly by the smallest prime factor:" if lang == "en" else "En küçük asal böleni tekrar tekrar bölelim:"
        return "number_theory/factorization", p, head + "\n" + "\n".join(steps) + final_line(f"{n} = {ans}", lang), ans, 2
    n = r.randint(10, 999)
    base = r.choice([2, 3, 5, 8, 16])
    digits, m, steps = [], n, []
    while m:
        steps.append(f"{m} ÷ {base} = {m // base} remainder {m % base}" if lang == "en"
                     else f"{m} ÷ {base} = {m // base}, kalan {m % base}")
        digits.append("0123456789ABCDEF"[m % base])
        m //= base
    res = "".join(reversed(digits))
    p = (f"Convert the decimal number {n} to base {base}." if lang == "en"
         else f"Onluk tabandaki {n} sayısını {base} tabanına çevirin.")
    tail = ("Reading the remainders from bottom to top gives " if lang == "en" else "Kalanları aşağıdan yukarıya okuyunca ") + f"{res}."
    return "number_theory/base_conversion", p, "\n".join(steps) + "\n" + tail + final_line(f"({res})_{base}", lang), res, 2


# --------------------------------------------------------------------------- dates, strings, units

WEEKDAYS = {"en": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
            "tr": ["Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi", "Pazar"]}
MONTHS = {"en": ["January", "February", "March", "April", "May", "June", "July", "August", "September",
                 "October", "November", "December"],
          "tr": ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim",
                 "Kasım", "Aralık"]}


def dstr(d, lang):
    return (f"{MONTHS['en'][d.month - 1]} {d.day}, {d.year}" if lang == "en"
            else f"{d.day} {MONTHS['tr'][d.month - 1]} {d.year}")


def gen_dates(r, lang):
    start = dt.date(r.randint(1990, 2035), r.randint(1, 12), r.randint(1, 28))
    delta = r.randint(1, 400)
    end = start + dt.timedelta(days=delta)
    if r.random() < 0.5:
        p = (f"How many days are there from {dstr(start, lang)} to {dstr(end, lang)} (counting the end date but not the start date)?"
             if lang == "en" else
             f"{dstr(start, lang)} ile {dstr(end, lang)} arasında kaç gün vardır (başlangıç günü sayılmaz, bitiş günü sayılır)?")
        steps = []
        cur = start
        while (cur.year, cur.month) != (end.year, end.month):
            nxt = (cur.replace(day=1) + dt.timedelta(days=32)).replace(day=1)
            steps.append((cur, nxt, (nxt - cur).days))
            cur = nxt
        steps.append((cur, end, (end - cur).days))
        body = "\n".join(f"{dstr(a, lang)} → {dstr(b, lang)}: {n}" for a, b, n in steps)
        sums = " + ".join(str(n) for _, _, n in steps)
        body += f"\n\n{sums} = {delta}" if len(steps) > 1 else ""
        return "dates/difference", p, body + final_line(delta, lang), delta, 2
    wd = WEEKDAYS[lang][start.weekday()]
    p = (f"{dstr(start, lang)} is a {wd}. What day of the week is it {delta} days later, and what is the date?"
         if lang == "en" else
         f"{dstr(start, lang)} bir {wd} günüdür. {delta} gün sonra haftanın hangi günüdür ve tarih nedir?")
    rem = delta % 7
    s = ((f"Weekdays repeat every 7 days: {delta} = 7 × {delta // 7} + {rem}, so we move {rem} weekday(s) forward from {wd}: "
          f"{WEEKDAYS[lang][end.weekday()]}.\nAdding {delta} days to {dstr(start, lang)} gives {dstr(end, lang)}.")
         if lang == "en" else
         (f"Haftanın günleri 7 günde bir tekrarlanır: {delta} = 7 × {delta // 7} + {rem}; {wd} gününden {rem} gün ileri gideriz: "
          f"{WEEKDAYS[lang][end.weekday()]}.\n{dstr(start, lang)} tarihine {delta} gün eklenince {dstr(end, lang)} olur."))
    ans = f"{WEEKDAYS[lang][end.weekday()]}, {dstr(end, lang)}"
    return "dates/weekday", p, s + final_line(ans, lang), ans, 2


WORDS_EN = ["strawberry", "mississippi", "bookkeeper", "banana", "assessment", "committee", "parallel",
            "occurrence", "programming", "possession", "necessary", "embarrass", "accommodation", "millennium",
            "independence", "successful", "referee", "balloon", "coffee", "tennessee", "giraffe", "letter"]
WORDS_TR = ["kahramanmaraş", "çekoslovakyalılaştıramadıklarımızdan", "anneanne", "kelebek", "merhaba",
            "dedikodu", "karakalem", "ilkokul", "bilgisayar", "üniversite", "saatçi", "kuşkonmaz", "sessizlik"]


def gen_strings(r, lang):
    kind = r.choice(["count", "count", "reverse", "sort", "wordcount"])
    if kind == "count":
        w = r.choice(WORDS_EN if lang == "en" else WORDS_TR)
        ch = r.choice(sorted(set(w)))
        n = w.count(ch)
        spelled = ", ".join(f"{c}{' ✓' if c == ch else ''}" for c in w)
        p = (f"How many times does the letter '{ch}' appear in the word \"{w}\"?" if lang == "en"
             else f"\"{w}\" kelimesinde '{ch}' harfi kaç kez geçer?")
        s = ((f"Spell the word letter by letter and mark each '{ch}':\n{spelled}\n\nThere are {n} marked letters.")
             if lang == "en" else
             (f"Kelimeyi harf harf yazıp her '{ch}' harfini işaretleyelim:\n{spelled}\n\nToplam {n} işaretli harf var."))
        return "strings/letter_count", p, s + final_line(n, lang), n, 1
    pool = (NAMES_EN + WORDS_EN) if lang == "en" else (NAMES_TR + WORDS_TR)
    ws = r.sample(pool, r.randint(4, 8))
    if kind == "reverse":
        res = " ".join(reversed(ws))
        p = (f"Reverse the order of the words (not the letters): {' '.join(ws)}" if lang == "en"
             else f"Kelimelerin sırasını tersine çevirin (harfleri değil): {' '.join(ws)}")
        s = ("Reading the words from last to first:\n" if lang == "en" else "Kelimeleri sondan başa okuyalım:\n") + \
            "\n".join(f"{i + 1}. {w}" for i, w in enumerate(reversed(ws)))
        return "strings/reverse_words", p, s + final_line(res, lang), res, 1
    if kind == "sort":
        if lang == "tr":
            alphabet = "abcçdefgğhıijklmnoöprsştuüvyz"
            sort_key = lambda w: [alphabet.index(c) if c in alphabet else 99 for c in w.replace("İ", "i").lower()]
        else:
            sort_key = str.casefold
        res = ", ".join(sorted(ws, key=sort_key))
        p = (f"Sort these words alphabetically: {', '.join(ws)}" if lang == "en"
             else f"Bu kelimeleri Türk alfabesine göre sıralayın: {', '.join(ws)}")
        s = ("Compare first letters, then later letters for ties:" if lang == "en"
             else "Önce ilk harfleri, eşitlik varsa sonraki harfleri Türk alfabesi sırasıyla karşılaştıralım (ç, ğ, ı, ö, ş, ü dahil):")
        return "strings/sort_words", p, s + "\n" + res + final_line(res, lang), res, 1
    sent = " ".join(ws)
    p = (f"How many words and how many characters (excluding spaces) are in: \"{sent}\"?" if lang == "en"
         else f"\"{sent}\" ifadesinde kaç kelime ve boşluklar hariç kaç karakter vardır?")
    lens = " + ".join(str(len(w)) for w in ws)
    total = sum(map(len, ws))
    s = ((f"Words: {len(ws)} ({', '.join(ws)}).\nCharacters per word: {lens} = {total}") if lang == "en"
         else (f"Kelimeler: {len(ws)} ({', '.join(ws)}).\nKelime başına karakter: {lens} = {total}"))
    ans = f"{len(ws)}, {total}"
    return "strings/word_count", p, s + final_line(ans, lang), ans, 1


UNITS = [  # (from, to, factor, en name from, en name to, tr from, tr to)
    ("km", "m", 1000, "kilometres", "metres", "kilometre", "metre"),
    ("m", "cm", 100, "metres", "centimetres", "metre", "santimetre"),
    ("kg", "g", 1000, "kilograms", "grams", "kilogram", "gram"),
    ("L", "mL", 1000, "litres", "millilitres", "litre", "mililitre"),
    ("h", "min", 60, "hours", "minutes", "saat", "dakika"),
    ("min", "s", 60, "minutes", "seconds", "dakika", "saniye"),
    ("m²", "cm²", 10000, "square metres", "square centimetres", "metrekare", "santimetrekare"),
]


def gen_units(r, lang):
    fr, to, k, ef, et, tf, tt = r.choice(UNITS)
    val = Fraction(r.randint(1, 400), r.choice([1, 2, 4, 10]))
    if r.random() < 0.5:
        res = val * k
        line = f"{fmt(val)} × {k} = {fmt(res)}"
        src, dst = fr, to
    else:
        val, res = val * k, val
        line = f"{fmt(val)} ÷ {k} = {fmt(res)}"
        src, dst = to, fr
    p = (f"Convert {fmt(val)} {src} to {dst}." if lang == "en" else f"{fmt(val)} {src} kaç {dst} eder?")
    s = (f"1 {fr} = {k} {to}.\n{line}" if lang == "en" else f"1 {fr} = {k} {to}.\n{line}")
    ans = f"{fmt(res)} {dst}"
    return "units/conversion", p, s + final_line(ans, lang), fmt(res), 1


# --------------------------------------------------------------------------- logic puzzles

def gen_logic(r, lang):
    n = r.choice([3, 4, 4, 5])
    people = r.sample(NAMES_EN if lang == "en" else NAMES_TR, n)
    target = list(people)
    r.shuffle(target)  # target[0] finishes first
    pos = {p: i for i, p in enumerate(target)}
    clue_pool = []
    for a, b in itertools.permutations(people, 2):
        if pos[a] < pos[b]:
            clue_pool.append(("before", a, b))
        if pos[a] + 1 == pos[b]:
            clue_pool.append(("right_before", a, b))
    for p_ in people:
        clue_pool.append(("place", p_, pos[p_]))
        if pos[p_] not in (0,):
            clue_pool.append(("not_first", p_, None))
        if pos[p_] != n - 1:
            clue_pool.append(("not_last", p_, None))
    r.shuffle(clue_pool)

    def ok(order, clue):
        k, a, b = clue
        pa = order.index(a)
        if k == "before":
            return pa < order.index(b)
        if k == "right_before":
            return pa + 1 == order.index(b)
        if k == "place":
            return pa == b
        if k == "not_first":
            return pa != 0
        return pa != n - 1

    clues = []
    for c in clue_pool:
        if c[0] == "place" and sum(x[0] == "place" for x in clues) >= 1:
            continue
        clues.append(c)
        sols = [o for o in itertools.permutations(people) if all(ok(o, cc) for cc in clues)]
        if len(sols) == 1:
            break
    sols = [o for o in itertools.permutations(people) if all(ok(o, cc) for cc in clues)]
    if len(sols) != 1:
        return gen_logic(r, lang)

    def say(c):
        k, a, b = c
        if k == "place":
            return f"{a} finished in position {b + 1}." if lang == "en" else f"{a} {b + 1}. sırada bitirdi."
        if lang == "en":
            return {"before": f"{a} finished before {b}.", "right_before": f"{a} finished immediately before {b}.",
                    "not_first": f"{a} did not finish first.", "not_last": f"{a} did not finish last."}[k]
        return {"before": f"{a}, {tr_ek(b, 'abl')} önce bitirdi.", "right_before": f"{a}, {tr_ek(b, 'abl')} hemen önce bitirdi.",
                "not_first": f"{a} birinci olmadı.", "not_last": f"{a} sonuncu olmadı."}[k]

    order = " > ".join(target)
    if lang == "en":
        p = f"{n} runners — {', '.join(people)} — finished a race with no ties. Clues:\n" + \
            "\n".join(f"- {say(c)}" for c in clues) + "\nWhat was the finishing order (first to last)?"
        s = (f"There are {math.factorial(n)} possible orders. Applying all {len(clues)} clues leaves exactly one order:\n"
             f"{order}\n\nVerification of each clue:\n" +
             "\n".join(f"- {say(c)} ✓ ({c[1]} is position {pos[c[1]] + 1}" +
                       (f", {c[2]} is position {pos[c[2]] + 1})" if c[0] in ('before', 'right_before') else ")")
                       for c in clues))
    else:
        p = f"{n} koşucu — {', '.join(people)} — bir yarışı beraberlik olmadan bitirdi. İpuçları:\n" + \
            "\n".join(f"- {say(c)}" for c in clues) + "\nBitiş sırası nedir (birinciden sonuncuya)?"
        s = (f"{math.factorial(n)} olası sıralama vardır. {len(clues)} ipucunun hepsini uygulayınca tek bir sıralama kalır:\n"
             f"{order}\n\nHer ipucunun kontrolü:\n" +
             "\n".join(f"- {say(c)} ✓ ({c[1]} {pos[c[1]] + 1}. sırada" +
                       (f", {c[2]} {pos[c[2]] + 1}. sırada)" if c[0] in ('before', 'right_before') else ")")
                       for c in clues))
    return "logic/ordering", p, s + final_line(order, lang), order, 3


# --------------------------------------------------------------------------- JSON extraction & unanswerable

CITIES = ["Istanbul", "Ankara", "Izmir", "Berlin", "Lisbon", "Toronto", "Nairobi", "Osaka", "Lima", "Oslo"]
JOBS_EN = ["engineer", "teacher", "nurse", "designer", "chef", "pilot", "lawyer", "farmer"]
JOBS_TR = ["mühendis", "öğretmen", "hemşire", "tasarımcı", "aşçı", "pilot", "avukat", "çiftçi"]


def gen_json(r, lang):
    name = r.choice(NAMES_EN if lang == "en" else NAMES_TR)
    age, city = r.randint(19, 70), r.choice(CITIES)
    job = r.choice(JOBS_EN if lang == "en" else JOBS_TR)
    langs = sorted(r.sample(["English", "Turkish", "German", "Spanish", "Japanese", "Arabic"], r.randint(1, 3)))
    rec = {"name": name, "age": age, "city": city, "occupation": job, "languages": langs}
    if lang == "en":
        text = (f"{name} is a {age}-year-old {job} who lives in {city}. "
                f"{name} speaks {', '.join(langs[:-1]) + ' and ' + langs[-1] if len(langs) > 1 else langs[0]}.")
        p = (f"Extract the information from the text into JSON with the keys name (string), age (integer), city (string), "
             f"occupation (string) and languages (array of strings, sorted alphabetically). Output only the JSON.\n\nText: {text}")
    else:
        text = (f"{name}, {tr_ek(city, 'loc')} yaşayan {age} yaşında bir {job}. "
                f"{name} şu dilleri konuşuyor: {', '.join(langs)}.")
        p = (f"Metindeki bilgileri name (metin), age (tam sayı), city (metin), occupation (metin) ve languages "
             f"(alfabetik sıralı metin dizisi) anahtarlarıyla JSON'a çıkarın. Yalnızca JSON yazın.\n\nMetin: {text}")
    out = json.dumps(rec, ensure_ascii=False, indent=2)
    return "json/extraction", p, f"```json\n{out}\n```", json.dumps(rec, ensure_ascii=False, sort_keys=True), 1


def gen_unanswerable(r, lang):
    n = r.choice(NAMES_EN if lang == "en" else NAMES_TR)
    a, pa = r.randint(2, 9), r.randint(2, 30)
    if lang == "en":
        p = (f"{n} buys {a} notebooks at ${pa} each and some pens. {n} pays with a $200 bill. "
             f"How much change does {n} receive?")
        s = (f"This cannot be determined from the information given. The notebooks cost {a} × {pa} = {a * pa} dollars, "
             f"but the problem does not say how many pens {n} bought or how much each pen costs, so the total cost "
             f"(and therefore the change) is unknown.\n\nIf you tell me the number of pens and their price, I can finish the calculation: "
             f"change = 200 - {a * pa} - (number of pens × price per pen).")
    else:
        p = (f"{n}, tanesi {pa} TL olan {a} defter ve birkaç kalem alıyor. {n} 200 TL ile ödeme yapıyor. "
             f"{n} ne kadar para üstü alır?")
        s = (f"Verilen bilgilerle bu soru cevaplanamaz. Defterlerin tutarı {a} × {pa} = {a * pa} TL'dir; ancak kaç kalem "
             f"alındığı ve kalemlerin fiyatı belirtilmemiş. Bu yüzden toplam tutar ve para üstü bilinemez.\n\n"
             f"Kalem sayısını ve fiyatını verirseniz hesabı tamamlayabilirim: para üstü = 200 - {a * pa} - (kalem sayısı × kalem fiyatı).")
    return "unanswerable/missing_info", p, s, "UNANSWERABLE", 2


# --------------------------------------------------------------------------- code (verified by tests)

CODE_TASKS = [
    dict(fn="fizz_buzz", args="n, a, b, wa, wb",
         en="Write a Python function `{fn}(n)` that returns a list of strings for the numbers 1..n, where multiples of {a} are replaced by \"{wa}\", multiples of {b} by \"{wb}\", and multiples of both by \"{wa}{wb}\".",
         tr="1'den n'e kadar sayılar için metin listesi döndüren `{fn}(n)` adında bir Python fonksiyonu yazın; {a} sayısının katları \"{wa}\", {b} sayısının katları \"{wb}\", ikisinin de katları \"{wa}{wb}\" olsun.",
         params=lambda r: dict(a=r.choice([2, 3, 4]), b=r.choice([5, 7]), wa=r.choice(["Fizz", "Foo", "Tik"]), wb=r.choice(["Buzz", "Bar", "Tak"])),
         code='''def {fn}(n):
    result = []
    for i in range(1, n + 1):
        word = ""
        if i % {a} == 0:
            word += "{wa}"
        if i % {b} == 0:
            word += "{wb}"
        result.append(word or str(i))
    return result''',
         tests="assert {fn}(1) == ['1']\nassert {fn}({a})[-1] == '{wa}'\nassert {fn}({b})[-1] == '{wb}'\nassert {fn}({a}*{b})[-1] == '{wa}{wb}'\nassert len({fn}(50)) == 50",
         names=["fizz_buzz", "tik_tak", "multiples_game"]),
    dict(fn="is_palindrome",
         en="Write a Python function `{fn}(s)` that returns True if the string is a palindrome when case and all non-alphanumeric characters are ignored.",
         tr="Büyük/küçük harf ve harf/rakam olmayan karakterler yok sayıldığında metin palindrom ise True döndüren `{fn}(s)` adında bir Python fonksiyonu yazın.",
         params=lambda r: {}, names=["is_palindrome", "palindrome_check", "reads_same_backwards"],
         code='''def {fn}(s):
    cleaned = [c.lower() for c in s if c.isalnum()]
    return cleaned == cleaned[::-1]''',
         tests="assert {fn}('A man, a plan, a canal: Panama')\nassert not {fn}('hello')\nassert {fn}('')\nassert {fn}('No lemon, no melon')"),
    dict(fn="two_sum",
         en="Write a Python function `{fn}(nums, target)` that returns the indices (i, j) with i < j of the two numbers that add up to target, or None if no such pair exists. It should run in O(n) time.",
         tr="Toplamı target olan iki sayının (i < j olacak şekilde) indekslerini (i, j) döndüren, böyle bir çift yoksa None döndüren `{fn}(nums, target)` adında O(n) zamanlı bir Python fonksiyonu yazın.",
         params=lambda r: {}, names=["two_sum", "pair_with_sum", "find_pair"],
         code='''def {fn}(nums, target):
    seen = {{}}
    for j, x in enumerate(nums):
        if target - x in seen:
            return (seen[target - x], j)
        seen.setdefault(x, j)
    return None''',
         tests="assert {fn}([2, 7, 11, 15], 9) == (0, 1)\nassert {fn}([3, 2, 4], 6) == (1, 2)\nassert {fn}([1, 2], 7) is None\nassert {fn}([3, 3], 6) == (0, 1)"),
    dict(fn="chunk",
         en="Write a Python function `{fn}(items, size)` that splits a list into consecutive chunks of length `size` (the last chunk may be shorter). Raise ValueError if size < 1.",
         tr="Bir listeyi `size` uzunluğunda ardışık parçalara bölen (son parça daha kısa olabilir) `{fn}(items, size)` adında bir Python fonksiyonu yazın. size < 1 ise ValueError fırlatsın.",
         params=lambda r: {}, names=["chunk", "split_into_chunks", "batched"],
         code='''def {fn}(items, size):
    if size < 1:
        raise ValueError("size must be at least 1")
    return [items[i:i + size] for i in range(0, len(items), size)]''',
         tests="assert {fn}([1,2,3,4,5], 2) == [[1,2],[3,4],[5]]\nassert {fn}([], 3) == []\ntry:\n    {fn}([1], 0)\n    raise AssertionError\nexcept ValueError:\n    pass"),
    dict(fn="caesar",
         en="Write a Python function `{fn}(text)` that applies a Caesar cipher with shift {k} to ASCII letters, preserving case and leaving other characters unchanged.",
         tr="ASCII harflere {k} kaydırmalı Sezar şifrelemesi uygulayan, büyük/küçük harfi koruyan ve diğer karakterleri değiştirmeyen `{fn}(text)` adında bir Python fonksiyonu yazın.",
         params=lambda r: dict(k=r.randint(1, 25)), names=["caesar", "shift_cipher", "encode_caesar"],
         code='''def {fn}(text):
    out = []
    for c in text:
        if "a" <= c <= "z":
            out.append(chr((ord(c) - 97 + {k}) % 26 + 97))
        elif "A" <= c <= "Z":
            out.append(chr((ord(c) - 65 + {k}) % 26 + 65))
        else:
            out.append(c)
    return "".join(out)''',
         tests="assert {fn}('') == ''\nassert {fn}('a') == chr((0+{k})%26+97)\nassert {fn}('Hi!')[2] == '!'\nassert {fn}('Z').isupper()"),
    dict(fn="rle_encode",
         en="Write a Python function `{fn}(s)` that run-length encodes a string, e.g. \"aaabcc\" -> \"a3b1c2\".",
         tr="Bir metni ardışık tekrar sayısıyla kodlayan `{fn}(s)` adında bir Python fonksiyonu yazın; örneğin \"aaabcc\" -> \"a3b1c2\".",
         params=lambda r: {}, names=["rle_encode", "run_length_encode", "compress"],
         code='''def {fn}(s):
    if not s:
        return ""
    parts, current, count = [], s[0], 1
    for c in s[1:]:
        if c == current:
            count += 1
        else:
            parts.append(f"{{current}}{{count}}")
            current, count = c, 1
    parts.append(f"{{current}}{{count}}")
    return "".join(parts)''',
         tests="assert {fn}('aaabcc') == 'a3b1c2'\nassert {fn}('') == ''\nassert {fn}('x') == 'x1'\nassert {fn}('abab') == 'a1b1a1b1'"),
    dict(fn="max_subarray",
         en="Write a Python function `{fn}(nums)` that returns the largest sum of a non-empty contiguous subarray (Kadane's algorithm).",
         tr="Boş olmayan ardışık bir alt dizinin en büyük toplamını döndüren `{fn}(nums)` adında bir Python fonksiyonu yazın (Kadane algoritması).",
         params=lambda r: {}, names=["max_subarray", "kadane", "best_window_sum"],
         code='''def {fn}(nums):
    best = current = nums[0]
    for x in nums[1:]:
        current = max(x, current + x)
        best = max(best, current)
    return best''',
         tests="assert {fn}([-2,1,-3,4,-1,2,1,-5,4]) == 6\nassert {fn}([-3,-1,-2]) == -1\nassert {fn}([5]) == 5"),
    dict(fn="roman_to_int",
         en="Write a Python function `{fn}(s)` that converts a Roman numeral (I, V, X, L, C, D, M, with subtractive notation) to an integer.",
         tr="Bir Roma rakamını (I, V, X, L, C, D, M; çıkarma kuralıyla) tam sayıya çeviren `{fn}(s)` adında bir Python fonksiyonu yazın.",
         params=lambda r: {}, names=["roman_to_int", "parse_roman", "from_roman"],
         code='''def {fn}(s):
    values = {{"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}}
    total = 0
    for i, c in enumerate(s):
        v = values[c]
        if i + 1 < len(s) and values[s[i + 1]] > v:
            total -= v
        else:
            total += v
    return total''',
         tests="assert {fn}('III') == 3\nassert {fn}('MCMXCIV') == 1994\nassert {fn}('XLII') == 42\nassert {fn}('IX') == 9"),
    dict(fn="balanced",
         en="Write a Python function `{fn}(s)` that returns True if every bracket in s ((), [], {{}}) is correctly matched and nested.",
         tr="s içindeki tüm parantezlerin ((), [], {{}}) doğru eşleşip iç içe geçtiği durumda True döndüren `{fn}(s)` adında bir Python fonksiyonu yazın.",
         params=lambda r: {}, names=["balanced", "brackets_ok", "is_valid_brackets"],
         code='''def {fn}(s):
    pairs = {{")": "(", "]": "[", "}}": "{{"}}
    stack = []
    for c in s:
        if c in "([{{":
            stack.append(c)
        elif c in pairs:
            if not stack or stack.pop() != pairs[c]:
                return False
    return not stack''',
         tests="assert {fn}('([]{{}})')\nassert not {fn}('([)]')\nassert not {fn}('((')\nassert {fn}('a(b)c')"),
    dict(fn="primes_up_to",
         en="Write a Python function `{fn}(n)` that returns all prime numbers <= n using the Sieve of Eratosthenes.",
         tr="Eratosthenes kalburu ile n'e eşit veya küçük tüm asal sayıları döndüren `{fn}(n)` adında bir Python fonksiyonu yazın.",
         params=lambda r: {}, names=["primes_up_to", "sieve", "list_primes"],
         code='''def {fn}(n):
    if n < 2:
        return []
    is_prime = [True] * (n + 1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(n ** 0.5) + 1):
        if is_prime[i]:
            for j in range(i * i, n + 1, i):
                is_prime[j] = False
    return [i for i, p in enumerate(is_prime) if p]''',
         tests="assert {fn}(1) == []\nassert {fn}(10) == [2,3,5,7]\nassert len({fn}(100)) == 25"),
    dict(fn="dedupe",
         en="Write a Python function `{fn}(items)` that removes duplicates from a list while preserving the order of first occurrence.",
         tr="Bir listedeki tekrarları, ilk görülme sırasını koruyarak kaldıran `{fn}(items)` adında bir Python fonksiyonu yazın.",
         params=lambda r: {}, names=["dedupe", "unique_in_order", "remove_duplicates"],
         code='''def {fn}(items):
    seen = set()
    result = []
    for x in items:
        if x not in seen:
            seen.add(x)
            result.append(x)
    return result''',
         tests="assert {fn}([3,1,3,2,1]) == [3,1,2]\nassert {fn}([]) == []\nassert {fn}(list('abca')) == ['a','b','c']"),
    dict(fn="moving_average",
         en="Write a Python function `{fn}(values)` that returns the list of moving averages over a window of {k} consecutive values (an empty list if there are fewer than {k} values).",
         tr="{k} ardışık değerlik pencere üzerinden hareketli ortalamaların listesini döndüren (değer sayısı {k} değerden azsa boş liste) `{fn}(values)` adında bir Python fonksiyonu yazın.",
         params=lambda r: dict(k=r.randint(2, 5)), names=["moving_average", "rolling_mean", "window_avg"],
         code='''def {fn}(values):
    if len(values) < {k}:
        return []
    window = sum(values[:{k}])
    result = [window / {k}]
    for i in range({k}, len(values)):
        window += values[i] - values[i - {k}]
        result.append(window / {k})
    return result''',
         tests="assert {fn}([1]*{k}) == [1.0]\nassert {fn}([]) == []\nassert len({fn}(list(range(10)))) == 10 - {k} + 1\nassert abs({fn}(list(range(10)))[0] - sum(range({k}))/{k}) < 1e-9"),
    dict(fn="longest_common_prefix",
         en="Write a Python function `{fn}(words)` that returns the longest common prefix of a list of strings (empty string for an empty list).",
         tr="Bir metin listesinin en uzun ortak önekini döndüren (liste boşsa boş metin) `{fn}(words)` adında bir Python fonksiyonu yazın.",
         params=lambda r: {}, names=["longest_common_prefix", "common_prefix", "shared_start"],
         code='''def {fn}(words):
    if not words:
        return ""
    prefix = min(words, key=len)
    for w in words:
        while not w.startswith(prefix):
            prefix = prefix[:-1]
    return prefix''',
         tests="assert {fn}(['flower','flow','flight']) == 'fl'\nassert {fn}(['dog','car']) == ''\nassert {fn}([]) == ''\nassert {fn}(['a']) == 'a'"),
    dict(fn="binary_search",
         en="Write a Python function `{fn}(sorted_list, target)` that returns the index of target in a sorted list using binary search, or -1 if it is absent.",
         tr="Sıralı bir listede ikili arama ile target'ın indeksini döndüren, yoksa -1 döndüren `{fn}(sorted_list, target)` adında bir Python fonksiyonu yazın.",
         params=lambda r: {}, names=["binary_search", "bsearch", "find_sorted"],
         code='''def {fn}(sorted_list, target):
    lo, hi = 0, len(sorted_list) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if sorted_list[mid] == target:
            return mid
        if sorted_list[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1''',
         tests="assert {fn}([1,3,5,7,9], 7) == 3\nassert {fn}([1,3,5], 4) == -1\nassert {fn}([], 1) == -1\nassert {fn}([2], 2) == 0"),
    dict(fn="word_frequencies",
         en="Write a Python function `{fn}(text)` that returns a dict mapping each lowercase word to its count. Words are sequences of letters; ignore punctuation.",
         tr="Her küçük harfli kelimeyi tekrar sayısına eşleyen bir sözlük döndüren `{fn}(text)` adında bir Python fonksiyonu yazın. Kelimeler harf dizileridir; noktalama yok sayılsın.",
         params=lambda r: {}, names=["word_frequencies", "count_words", "word_histogram"],
         code='''import re
from collections import Counter


def {fn}(text):
    return dict(Counter(re.findall(r"[^\\W\\d_]+", text.lower())))''',
         tests="assert {fn}('The cat, the hat.') == {{'the': 2, 'cat': 1, 'hat': 1}}\nassert {fn}('') == {{}}"),
]


def run_python_tests(code, tests, timeout=10):
    with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as fh:
        fh.write(code + "\n\n" + tests + "\n")
        path = fh.name
    try:
        res = subprocess.run([sys.executable, "-I", path], capture_output=True, timeout=timeout)
        return res.returncode == 0
    except subprocess.TimeoutExpired:
        return False


def gen_code(r, lang):
    task = r.choice(CODE_TASKS)
    params = task["params"](r)
    fn = r.choice(task["names"])
    params["fn"] = fn
    prompt = task[lang].format(**params)
    code = task["code"].format(**params)
    tests = task["tests"].format(**params)
    if lang == "en":
        resp = (f"```python\n{code}\n```\n\nHow it works: the function handles the edge cases explicitly and processes the input "
                f"in a single pass where possible. Quick tests:\n\n```python\n{tests}\n```")
    else:
        resp = (f"```python\n{code}\n```\n\nNasıl çalışır: fonksiyon uç durumları açıkça ele alır ve mümkün olduğunda girdiyi tek "
                f"geçişte işler. Hızlı testler:\n\n```python\n{tests}\n```")
    return "code/python/" + task["fn"], prompt, resp, code, 2, tests


# --------------------------------------------------------------------------- driver

FAMILIES = {
    "word_problem": (gen_word_problem, 0.30),
    "arithmetic": (gen_arithmetic, 0.07),
    "algebra": (gen_algebra, 0.10),
    "number_theory": (gen_number_theory, 0.07),
    "dates": (gen_dates, 0.06),
    "strings": (gen_strings, 0.08),
    "units": (gen_units, 0.04),
    "logic": (gen_logic, 0.08),
    "json": (gen_json, 0.06),
    "unanswerable": (gen_unanswerable, 0.04),
    "code": (gen_code, 0.10),
}


def generate(n, seed=0, tr_ratio=0.35, verify_code=True):
    """Yield up to n unique verified examples."""
    r = random.Random(seed)
    names, weights = zip(*[(k, w) for k, (_, w) in FAMILIES.items()])
    seen, made, code_cache = set(), 0, {}
    attempts = 0
    while made < n and attempts < n * 20:
        attempts += 1
        fam = r.choices(names, weights)[0]
        lang = "tr" if r.random() < tr_ratio else "en"
        out = FAMILIES[fam][0](r, lang)
        if fam == "code":
            sub, p, s, ans, d, tests = out
            ck = (ans, tests)
            if verify_code:
                if ck not in code_cache:
                    code_cache[ck] = run_python_tests(ans, tests)
                if not code_cache[ck]:
                    continue
            ans = "CODE_VERIFIED_BY_TESTS"
            extra = {"tests": tests}
        else:
            extra = None
            sub, p, s, ans, d = out
            if check_arithmetic(s):
                continue
        if p in seen:
            continue
        seen.add(p)
        made += 1
        yield example(sub, lang, p, s, ans, seed, d, extra)


def corrupt(ex, r):
    """Build a plausible but wrong response for preference pairs: perturb one result line."""
    lines = ex["response"].split("\n")
    idx = [i for i, l in enumerate(lines) if re.search(r"= -?\d", l)]
    if not idx:
        return None
    i = r.choice(idx)
    m = list(re.finditer(r"= (-?\d+(?:\.\d+)?)", lines[i]))[-1]
    val = Fraction(m.group(1))
    wrong = val + r.choice([-10, -3, -2, -1, 1, 2, 3, 10]) * (1 if val.denominator == 1 else Fraction(1, 10))
    lines[i] = lines[i][:m.start(1)] + fmt(wrong) + lines[i][m.end(1):]
    bad = "\n".join(lines[:i + 1])
    tail = "**Answer:**" if ex["language"] == "en" else "**Cevap:**"
    bad += f"\n\n{tail} {fmt(wrong)}"
    return bad