Spaces:
Paused

File size: 30,961 Bytes
f78142c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Deterministic, original Pearson Edexcel IAL M1-style question generation.

The generators deliberately create new parameter combinations.  They do not
ship, transcribe, or reproduce the source examination papers.
"""

from __future__ import annotations

from dataclasses import asdict, dataclass, field
from math import atan2, cos, degrees, radians, sin, sqrt
import random
import time
from typing import Any, Callable


G = 9.8

TOPICS = {
    "Mixed mission": "mixed",
    "Kinematics · vertical motion": "vertical",
    "Kinematics · speed–time graph": "speed_time",
    "Momentum · impulse & collision": "collision",
    "Statics · moments on a beam": "beam",
    "Forces · rough horizontal plane": "friction",
    "Forces · connected particles": "connected",
    "Vectors · 2D motion & bearings": "vectors",
    "Equilibrium · strings & forces": "equilibrium",
}

DIFFICULTIES = ("Foundation", "Exam standard", "Challenge")


@dataclass
class Question:
    id: str
    seed: int
    topic: str
    topic_label: str
    difficulty: str
    title: str
    prompt: str
    marks: int
    expected_answers: list[dict[str, Any]]
    solution_steps: list[str]
    mark_scheme: list[dict[str, Any]]
    theory_key: str
    hints: list[str]
    diagram_kind: str
    diagram_data: dict[str, Any]
    common_errors: list[dict[str, Any]] = field(default_factory=list)
    source_note: str = (
        "Original procedural question inspired by the assessed skills and "
        "command-word patterns in the supplied M1 paper collection."
    )

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)


def _answer(
    key: str,
    label: str,
    value: float,
    unit: str = "",
    tolerance: float | None = None,
    precision: int = 3,
) -> dict[str, Any]:
    if tolerance is None:
        tolerance = max(0.015, abs(value) * 0.008)
    return {
        "key": key,
        "label": label,
        "value": float(value),
        "unit": unit,
        "tolerance": float(tolerance),
        "display": f"{value:.{precision}g}{(' ' + unit) if unit else ''}",
    }


def _qid(topic: str, seed: int) -> str:
    return f"M1-{topic[:3].upper()}-{seed % 1_000_000:06d}"


def _collision(rng: random.Random, difficulty: str, seed: int) -> Question:
    m1 = rng.randint(2, 6)
    m2 = rng.randint(3, 8)
    u1 = rng.randint(6, 11)
    u2 = rng.randint(0, 4)
    v = (m1 * u1 + m2 * u2) / (m1 + m2)
    impulse = m1 * (u1 - v)
    energy_loss = 0.5 * m1 * u1**2 + 0.5 * m2 * u2**2 - 0.5 * (m1 + m2) * v**2

    parts = [
        "(a) Find the common speed immediately after impact.",
        "(b) Find the magnitude of the impulse exerted on particle $P$.",
    ]
    answers = [
        _answer("v", "common speed", v, r"m s$^{-1}$"),
        _answer("J", "impulse", impulse, "N s"),
    ]
    steps = [
        "Choose the direction of motion as positive and keep that sign convention throughout.",
        rf"Conservation of momentum: ${m1}({u1})+{m2}({u2})=({m1}+{m2})v$.",
        rf"Hence $v={v:.4g}\,\mathrm{{m\,s^{{-1}}}}$.",
        rf"Impulse on $P$ is the magnitude of its change in momentum: "
        rf"$J=|{m1}v-{m1}({u1})|={impulse:.4g}\,\mathrm{{N\,s}}$.",
    ]
    marks = 6
    if difficulty == "Foundation":
        parts = parts[:1]
        answers = answers[:1]
        steps = steps[:3]
        marks = 3
    elif difficulty == "Challenge":
        parts.append("(c) Calculate the kinetic energy lost in the collision.")
        answers.append(_answer("E", "kinetic energy lost", energy_loss, "J"))
        steps.append(
            rf"Energy lost $=\tfrac12({m1})({u1})^2+\tfrac12({m2})({u2})^2"
            rf"-\tfrac12({m1+m2})({v:.4g})^2={energy_loss:.4g}\,\mathrm{{J}}$."
        )
        marks = 9

    prompt = rf"""
Two particles $P$ and $Q$, of masses ${m1}\,\mathrm{{kg}}$ and
${m2}\,\mathrm{{kg}}$ respectively, move in the same direction along a smooth
horizontal line. Immediately before a direct collision their speeds are
${u1}\,\mathrm{{m\,s^{{-1}}}}$ and ${u2}\,\mathrm{{m\,s^{{-1}}}}$ respectively.
They join together on impact.

{chr(10).join(parts)}
"""
    return Question(
        id=_qid("collision", seed), seed=seed, topic="collision",
        topic_label="Momentum · impulse & collision", difficulty=difficulty,
        title="Impact Dock", prompt=prompt, marks=marks,
        expected_answers=answers, solution_steps=steps,
        mark_scheme=[
            {"step": "Consistent signed momentum equation", "marks": 2},
            {"step": "Correct common velocity", "marks": 1},
            {"step": "Impulse as change in momentum", "marks": 3},
        ],
        theory_key="collision",
        hints=[
            "Draw velocity arrows and declare one direction positive.",
            "With no external horizontal impulse, total momentum before equals total momentum after.",
            "Impulse is $|m(v-u)|$ for the chosen particle—not total momentum.",
        ],
        diagram_kind="collision",
        diagram_data={"m1": m1, "m2": m2, "u1": u1, "u2": u2, "v": v},
        common_errors=[
            {
                "value": (m1 * u1 - m2 * u2) / (m1 + m2),
                "title": "A sign was reversed unnecessarily",
                "explanation": "Both particles initially move in the same direction, so both initial momenta have the same sign.",
            },
            {
                "value": m1 * v,
                "title": "Momentum was used instead of impulse",
                "explanation": "Impulse is the change $m(v-u)$, not the final momentum $mv$.",
            },
        ],
    )


def _vertical(rng: random.Random, difficulty: str, seed: int) -> Question:
    u = rng.choice([14, 16, 18, 20, 22, 24])
    h = rng.randint(4, 14)
    impact_speed = sqrt(u**2 + 2 * G * h)
    time_to_ground = (u + impact_speed) / G
    max_height = h + u**2 / (2 * G)
    parts = [
        "(a) Find the speed of the particle immediately before it strikes the ground.",
        "(b) Find the total time from projection until it first strikes the ground.",
    ]
    answers = [
        _answer("v", "impact speed", impact_speed, r"m s$^{-1}$"),
        _answer("t", "time to ground", time_to_ground, "s"),
    ]
    steps = [
        "Take upward as positive. Then $u>0$, $a=-9.8$ and the displacement to the ground is negative.",
        rf"Use $v^2=u^2+2as$: $v^2={u}^2+2(-9.8)(-{h})$.",
        rf"The required speed is $|v|={impact_speed:.4g}\,\mathrm{{m\,s^{{-1}}}}$.",
        rf"Use $s=ut+\tfrac12at^2$: $-{h}={u}t-4.9t^2$ and keep the positive root.",
        rf"Therefore $t={time_to_ground:.4g}\,\mathrm{{s}}$.",
    ]
    marks = 6
    if difficulty == "Foundation":
        parts = parts[:1]
        answers = answers[:1]
        steps = steps[:3]
        marks = 3
    elif difficulty == "Challenge":
        parts.append("(c) Find the greatest height reached above the ground.")
        answers.append(_answer("H", "greatest height", max_height, "m"))
        steps.append(
            rf"At greatest height $v=0$, so the rise is $u^2/(2g)$ and "
            rf"$H={h}+{u}^2/(19.6)={max_height:.4g}\,\mathrm{{m}}$."
        )
        marks = 9

    prompt = rf"""
A small stone is projected vertically upwards with speed
${u}\,\mathrm{{m\,s^{{-1}}}}$ from a point $O$ that is ${h}\,\mathrm{{m}}$
above horizontal ground. The stone is modelled as a particle moving freely
under gravity. Take $g=9.8\,\mathrm{{m\,s^{{-2}}}}$.

{chr(10).join(parts)}
"""
    return Question(
        id=_qid("vertical", seed), seed=seed, topic="vertical",
        topic_label="Kinematics · vertical motion", difficulty=difficulty,
        title="Gravity Launch", prompt=prompt, marks=marks,
        expected_answers=answers, solution_steps=steps,
        mark_scheme=[
            {"step": "Consistent sign convention", "marks": 1},
            {"step": "Correct SUVAT substitution", "marks": 2},
            {"step": "Positive physical root and units", "marks": 3},
        ],
        theory_key="vertical",
        hints=[
            "Write a sign table for $u$, $v$, $a$ and $s$ before choosing a SUVAT equation.",
            "The displacement from the launch point to the ground is $-h$ if up is positive.",
            "A quadratic time equation gives two mathematical roots; time must be positive.",
        ],
        diagram_kind="vertical",
        diagram_data={"u": u, "h": h, "impact_speed": impact_speed, "t": time_to_ground, "max_height": max_height},
        common_errors=[
            {
                "value": sqrt(max(0, u**2 - 2 * G * h)),
                "title": "The displacement sign was lost",
                "explanation": "With upward positive, both $a$ and the displacement to the ground are negative, so $2as$ is positive.",
            },
            {
                "value": u / G,
                "title": "Only the time to the top was found",
                "explanation": "$u/g$ is the ascent time to maximum height, not the full time to the ground.",
            },
        ],
    )


def _speed_time(rng: random.Random, difficulty: str, seed: int) -> Question:
    speed = rng.choice([15, 18, 20, 24])
    t_acc = rng.choice([8, 10, 12, 15, 20])
    t_const = rng.choice([60, 90, 120, 180])
    t_dec = 2 * t_acc
    distance = 0.5 * speed * t_acc + speed * t_const + 0.5 * speed * t_dec
    acceleration = speed / t_acc
    average_speed = distance / (t_acc + t_const + t_dec)
    parts = [
        "(a) Sketch a speed–time graph for the complete journey.",
        "(b) Find $T$.",
        "(c) Find the acceleration during the first $T$ seconds.",
    ]
    answers = [
        _answer("T", "acceleration time", t_acc, "s", tolerance=0.05),
        _answer("a", "initial acceleration", acceleration, r"m s$^{-2}$"),
    ]
    steps = [
        "The graph is a trapezium: linear rise, constant-speed section, then a gentler linear fall.",
        rf"Because the acceleration magnitude is twice the deceleration magnitude, the deceleration time is $2T$.",
        rf"Distance is area under the graph: ${distance:g}=\tfrac12({speed})T+({speed})({t_const})+\tfrac12({speed})(2T)$.",
        rf"Solving gives $T={t_acc}\,\mathrm{{s}}$.",
        rf"Initial acceleration $=\Delta v/\Delta t={speed}/{t_acc}={acceleration:.4g}\,\mathrm{{m\,s^{{-2}}}}$.",
    ]
    marks = 8
    if difficulty == "Foundation":
        parts = parts[:2]
        answers = answers[:1]
        steps = steps[:4]
        marks = 6
    elif difficulty == "Challenge":
        parts.append("(d) Find the average speed for the complete journey.")
        answers.append(_answer("v_avg", "average speed", average_speed, r"m s$^{-1}$"))
        steps.append(
            rf"Average speed $={distance:g}/({t_acc}+{t_const}+{t_dec})={average_speed:.4g}\,\mathrm{{m\,s^{{-1}}}}$."
        )
        marks = 10
    prompt = rf"""
A train starts from rest and accelerates uniformly for $T$ seconds until it
reaches ${speed}\,\mathrm{{m\,s^{{-1}}}}$. It travels at this constant speed
for ${t_const}$ seconds and then decelerates uniformly to rest. The magnitude
of its acceleration is twice the magnitude of its deceleration. The stations
are ${distance/1000:.3g}\,\mathrm{{km}}$ apart.

{chr(10).join(parts)}
"""
    return Question(
        id=_qid("speed_time", seed), seed=seed, topic="speed_time",
        topic_label="Kinematics · speed–time graph", difficulty=difficulty,
        title="Velocity Valley", prompt=prompt, marks=marks,
        expected_answers=answers, solution_steps=steps,
        mark_scheme=[
            {"step": "Correct three-section graph", "marks": 3},
            {"step": "Area equals distance", "marks": 3},
            {"step": "Acceleration from gradient", "marks": 2},
        ],
        theory_key="speed_time",
        hints=[
            "On a speed–time graph, gradient is acceleration and area is distance.",
            "Half the deceleration magnitude means twice the deceleration time for the same speed change.",
            "Split the area into two triangles and one rectangle.",
        ],
        diagram_kind="speed_time",
        diagram_data={"speed": speed, "t_acc": t_acc, "t_const": t_const, "t_dec": t_dec, "distance": distance},
        common_errors=[
            {
                "value": (distance - speed * t_const) / speed,
                "title": "The triangular halves were not included",
                "explanation": "Each acceleration/deceleration section is triangular, so its area is $\tfrac12\times$ base $\times$ height.",
            }
        ],
    )


def _beam(rng: random.Random, difficulty: str, seed: int) -> Question:
    length = rng.choice([6, 8, 10])
    separation = rng.choice([2, 3, 4])
    ratio = rng.choice([2, 3, 4])
    x = length / 2 - separation / (ratio + 1)
    while x <= 0.5 or x + separation >= length - 0.5:
        separation = rng.choice([2, 3])
        ratio = rng.choice([2, 3])
        x = length / 2 - separation / (ratio + 1)
    base = rng.choice([18, 20, 24, 30])
    weight = (ratio + 1) * base
    t_d = base
    t_c = ratio * base
    parts = [
        "(a) Find the tension in the rope attached at $D$.",
        "(b) Find the value of $x$.",
    ]
    answers = [
        _answer("T_D", "tension at D", t_d, "N", tolerance=0.05),
        _answer("x", "distance AC", x, "m"),
    ]
    steps = [
        rf"Vertical equilibrium gives $T_C+T_D={weight}$ and $T_C={ratio}T_D$.",
        rf"Therefore $T_D={weight}/({ratio}+1)={t_d}\,\mathrm{{N}}$ and $T_C={t_c}\,\mathrm{{N}}$.",
        rf"Take moments about $A$: ${t_c}x+{t_d}(x+{separation})={weight}({length}/2)$.",
        rf"Solving gives $x={x:.4g}\,\mathrm{{m}}$.",
    ]
    prompt = rf"""
A uniform beam $AB$ has length ${length}\,\mathrm{{m}}$ and weight
${weight}\,\mathrm{{N}}$. It is suspended horizontally in equilibrium by two
light vertical ropes attached at $C$ and $D$, where $AC=x\,\mathrm{{m}}$ and
$CD={separation}\,\mathrm{{m}}$. The tension at $C$ is ${ratio}$ times the
tension at $D$.

{chr(10).join(parts)}
"""
    if difficulty == "Foundation":
        prompt = prompt.replace("\n(b) Find the value of $x$.", "")
        answers = answers[:1]
        steps = steps[:2]
        marks = 3
    else:
        marks = 6 if difficulty == "Exam standard" else 7
    return Question(
        id=_qid("beam", seed), seed=seed, topic="beam",
        topic_label="Statics · moments on a beam", difficulty=difficulty,
        title="Balance Bridge", prompt=prompt, marks=marks,
        expected_answers=answers, solution_steps=steps,
        mark_scheme=[
            {"step": "Vertical force equilibrium", "marks": 2},
            {"step": "Moment equation about a named point", "marks": 2},
            {"step": "Correct distances and solution", "marks": 2},
        ],
        theory_key="beam",
        hints=[
            "For equilibrium, both resultant force and resultant moment are zero.",
            "The beam is uniform, so its weight acts at the midpoint of $AB$.",
            "Taking moments about $A$ keeps every distance measured from the same point.",
        ],
        diagram_kind="beam",
        diagram_data={"length": length, "separation": separation, "x": x, "weight": weight, "ratio": ratio, "tc": t_c, "td": t_d},
        common_errors=[
            {
                "value": length / 2 - separation / ratio,
                "title": "The two support moments were not combined correctly",
                "explanation": "Both tensions create moments about $A$; the distance of $D$ is $x+CD$, not just $CD$.",
            }
        ],
    )


def _friction(rng: random.Random, difficulty: str, seed: int) -> Question:
    mass = rng.choice([4, 5, 6, 8, 10])
    mu = rng.choice([0.25, 0.3, 0.4, 0.5])
    theta = rng.choice([20, 30, 35, 40])
    th = radians(theta)
    force = mu * mass * G / (cos(th) + mu * sin(th))
    reaction = mass * G - force * sin(th)
    wrong_no_vertical = mu * mass * G / cos(th)
    wrong_sign = mu * mass * G / max(0.05, cos(th) - mu * sin(th))
    answers = [
        _answer("P", "limiting pulling force", force, "N"),
        _answer("R", "normal reaction", reaction, "N"),
    ]
    parts = [
        "(a) Find the value of $P$ for which the block is on the point of moving.",
        "(b) Find the corresponding normal reaction.",
    ]
    steps = [
        rf"Vertical equilibrium: $R+P\sin {theta}^\circ={mass}g$, so $R={mass}g-P\sin {theta}^\circ$.",
        rf"At limiting equilibrium, $F=\mu R={mu}R$.",
        rf"Horizontal equilibrium: $P\cos {theta}^\circ={mu}({mass}g-P\sin {theta}^\circ)$.",
        rf"Hence $P={force:.4g}\,\mathrm{{N}}$ and $R={reaction:.4g}\,\mathrm{{N}}$.",
    ]
    marks = 7
    if difficulty == "Foundation":
        parts = parts[:1]
        answers = answers[:1]
        marks = 5
    elif difficulty == "Challenge":
        parts.append("(c) Explain why the normal reaction is not equal to the weight.")
        steps.append("The upward component of the applied force supports part of the weight, reducing $R$.")
        marks = 9
    prompt = rf"""
A small block of mass ${mass}\,\mathrm{{kg}}$ rests on a rough horizontal plane.
The coefficient of friction between the block and the plane is $\mu={mu}$.
A force of magnitude $P\,\mathrm{{N}}$ acts at ${theta}^\circ$ above the
horizontal. The block is modelled as a particle and is in limiting equilibrium.

{chr(10).join(parts)}
"""
    return Question(
        id=_qid("friction", seed), seed=seed, topic="friction",
        topic_label="Forces · rough horizontal plane", difficulty=difficulty,
        title="Friction Frontier", prompt=prompt, marks=marks,
        expected_answers=answers, solution_steps=steps,
        mark_scheme=[
            {"step": "Correct normal reaction equation", "marks": 2},
            {"step": r"Use of limiting friction $F=\mu R$", "marks": 2},
            {"step": "Horizontal equilibrium and answer", "marks": 3},
        ],
        theory_key="friction",
        hints=[
            "Resolve the applied force both horizontally and vertically.",
            "Because the force pulls upward, it reduces the normal reaction.",
            r"Only at impending slip may you write $F=\mu R$.",
        ],
        diagram_kind="friction",
        diagram_data={"mass": mass, "mu": mu, "theta": theta, "force": force, "reaction": reaction},
        common_errors=[
            {
                "value": wrong_no_vertical,
                "title": "The vertical component of $P$ was ignored",
                "explanation": r"The pull partly supports the block, so $R=mg-P\sin\theta$, not $mg$.",
            },
            {
                "value": wrong_sign,
                "title": "The pull was made to increase the reaction",
                "explanation": r"An upward pull reduces the normal reaction; the $P\sin\theta$ term must be subtracted from $mg$.",
            },
        ],
    )


def _connected(rng: random.Random, difficulty: str, seed: int) -> Question:
    sin_a, cos_a, tan_text, angle = 3 / 5, 4 / 5, "3/4", degrees(atan2(3, 4))
    mu = rng.choice([0.2, 0.25, 0.3])
    for _ in range(30):
        m1 = rng.choice([4, 5, 6, 8])
        m2 = rng.choice([5, 6, 7, 8, 9])
        a = G * (m2 - m1 * (sin_a + mu * cos_a)) / (m1 + m2)
        if 0.4 < a < 5:
            break
    tension = m2 * (G - a)
    answers = [
        _answer("a", "acceleration", a, r"m s$^{-2}$"),
        _answer("T", "tension", tension, "N"),
    ]
    steps = [
        "Since the hanging mass descends, the block on the plane moves up; friction on it acts down the plane.",
        rf"For $A$ up the plane: $T-{m1}g\sin\alpha-{mu}({m1}g\cos\alpha)={m1}a$.",
        rf"For $B$ downward: ${m2}g-T={m2}a$.",
        rf"Adding eliminates $T$ and gives $a={a:.4g}\,\mathrm{{m\,s^{{-2}}}}$.",
        rf"Substitution gives $T={m2}(9.8-{a:.4g})={tension:.4g}\,\mathrm{{N}}$.",
    ]
    parts = [
        "(a) Write down an equation of motion for each particle.",
        "(b) Find the magnitude of the acceleration.",
        "(c) Find the tension in the string.",
    ]
    marks = 9
    if difficulty == "Foundation":
        parts = parts[:2]
        answers = answers[:1]
        steps = steps[:4]
        marks = 6
    elif difficulty == "Challenge":
        parts.append("(d) State two modelling assumptions used when forming the equations.")
        steps.append("A light inextensible string gives a common acceleration and a small smooth pulley gives the same tension on both sides.")
        marks = 11
    prompt = rf"""
A particle $A$ of mass ${m1}\,\mathrm{{kg}}$ rests on a rough plane inclined
at angle $\alpha$ to the horizontal, where $\tan\alpha={tan_text}$. It is
connected by a light inextensible string over a small smooth pulley to a
hanging particle $B$ of mass ${m2}\,\mathrm{{kg}}$. The coefficient of friction
between $A$ and the plane is $\mu={mu}$. The system is released from rest and
$B$ moves downwards. Take $g=9.8\,\mathrm{{m\,s^{{-2}}}}$.

{chr(10).join(parts)}
"""
    return Question(
        id=_qid("connected", seed), seed=seed, topic="connected",
        topic_label="Forces · connected particles", difficulty=difficulty,
        title="Pulley Peak", prompt=prompt, marks=marks,
        expected_answers=answers, solution_steps=steps,
        mark_scheme=[
            {"step": r"Correct friction direction and $R=mg\cos\alpha$", "marks": 3},
            {"step": "One equation for each particle", "marks": 3},
            {"step": "Eliminate tension and solve", "marks": 3},
        ],
        theory_key="connected",
        hints=[
            "Friction opposes the stated motion, so it acts down the plane on $A$.",
            "For a light inextensible string, both particles have the same acceleration magnitude.",
            "Add the two equations of motion to eliminate tension.",
        ],
        diagram_kind="connected",
        diagram_data={"m1": m1, "m2": m2, "mu": mu, "angle": angle, "sin": sin_a, "cos": cos_a, "a": a, "tension": tension},
        common_errors=[
            {
                "value": G * (m2 - m1 * (sin_a - mu * cos_a)) / (m1 + m2),
                "title": "Friction was put in the direction of motion",
                "explanation": "Because $A$ moves up the plane, friction acts down the plane and joins the downslope component of weight.",
            }
        ],
    )


def _vectors(rng: random.Random, difficulty: str, seed: int) -> Question:
    ux = rng.choice([4, 5, 6, 8, 10, 12])
    uy = rng.choice([-8, -6, -4, 3, 5])
    ax = rng.choice([-3, -2, 1, 2])
    ay = rng.choice([-1, 1, 2, 3])
    t = rng.choice([3, 4, 5, 6])
    vx, vy = ux + ax * t, uy + ay * t
    if abs(vx) + abs(vy) < 2:
        vx += 4
        ux += 4
    speed = sqrt(vx**2 + vy**2)
    bearing = (degrees(atan2(vx, vy)) + 360) % 360
    answers = [
        _answer("v_x", "$i$ component", vx, r"m s$^{-1}$", tolerance=0.05),
        _answer("v_y", "$j$ component", vy, r"m s$^{-1}$", tolerance=0.05),
        _answer("speed", "speed", speed, r"m s$^{-1}$"),
        _answer("bearing", "bearing", bearing, "°", tolerance=0.7),
    ]
    parts = [
        rf"(a) Find the velocity of $P$ when $t={t}\,\mathrm{{s}}$, in terms of $\mathbf i$ and $\mathbf j$.",
        "(b) Find its speed at this instant.",
        "(c) Find its direction of motion as a three-figure bearing.",
    ]
    steps = [
        rf"Use $\mathbf v=\mathbf u+t\mathbf a$: $\mathbf v=({ux}\mathbf i+{uy}\mathbf j)+{t}({ax}\mathbf i+{ay}\mathbf j)$.",
        rf"Thus $\mathbf v={vx}\mathbf i+{vy}\mathbf j\,\mathrm{{m\,s^{{-1}}}}$.",
        rf"Speed $=|\mathbf v|=\sqrt{{{vx}^2+{vy}^2}}={speed:.4g}\,\mathrm{{m\,s^{{-1}}}}$.",
        rf"A bearing is measured clockwise from north, giving ${bearing:.1f}^\circ$ (three-figure form ${bearing:03.0f}^\circ$).",
    ]
    marks = 8
    if difficulty == "Foundation":
        parts = parts[:2]
        answers = answers[:3]
        steps = steps[:3]
        marks = 5
    elif difficulty == "Challenge":
        parts.append("(d) Explain why the velocity vector, rather than the position vector, fixes the direction of motion.")
        steps.append(r"The tangent to the path is $d\mathbf r/dt=\mathbf v$; position only locates the particle relative to the origin.")
        marks = 10
    prompt = rf"""
The horizontal unit vectors $\mathbf i$ and $\mathbf j$ point due east and due
north respectively. A particle $P$ moves with constant acceleration
$({ax}\mathbf i+{ay}\mathbf j)\,\mathrm{{m\,s^{{-2}}}}$. At $t=0$ its velocity
is $({ux}\mathbf i+{uy}\mathbf j)\,\mathrm{{m\,s^{{-1}}}}$.

{chr(10).join(parts)}
"""
    return Question(
        id=_qid("vectors", seed), seed=seed, topic="vectors",
        topic_label="Vectors · 2D motion & bearings", difficulty=difficulty,
        title="Vector Voyage", prompt=prompt, marks=marks,
        expected_answers=answers, solution_steps=steps,
        mark_scheme=[
            {"step": r"Component form of $\mathbf v=\mathbf u+t\mathbf a$", "marks": 3},
            {"step": "Magnitude of velocity", "marks": 2},
            {"step": "Correct bearing convention", "marks": 3},
        ],
        theory_key="vectors",
        hints=[
            "Treat the east and north components as two simultaneous one-dimensional motions.",
            r"Speed is the magnitude of velocity: $\sqrt{v_x^2+v_y^2}$.",
            "Bearings start at north and turn clockwise; use the signs to identify the quadrant.",
        ],
        diagram_kind="vectors",
        diagram_data={"ux": ux, "uy": uy, "ax": ax, "ay": ay, "t": t, "vx": vx, "vy": vy, "speed": speed, "bearing": bearing},
        common_errors=[
            {
                "value": (degrees(atan2(vy, vx)) + 360) % 360,
                "title": "The mathematical angle was reported instead of a bearing",
                "explanation": "A standard Cartesian angle is measured anticlockwise from east; a bearing is clockwise from north.",
            }
        ],
    )


def _equilibrium(rng: random.Random, difficulty: str, seed: int) -> Question:
    weight = rng.choice([5, 8, 10, 12, 15])
    beta = rng.choice([30, 45, 60])
    force = weight * sin(radians(beta))
    tension = weight * cos(radians(beta))
    answers = [
        _answer("F", "perpendicular force", force, "N"),
        _answer("T", "string tension", tension, "N"),
    ]
    steps = [
        "The three forces are weight, string tension and the applied force. Draw all three from the particle.",
        rf"Resolve perpendicular to the string: $F={weight}\sin {beta}^\circ={force:.4g}\,\mathrm{{N}}$.",
        rf"Resolve along the string: $T={weight}\cos {beta}^\circ={tension:.4g}\,\mathrm{{N}}$.",
        "The two resolved equations are independent because the chosen axes are perpendicular.",
    ]
    parts = ["(a) Find $F$.", "(b) Find the tension in the string."]
    marks = 6
    if difficulty == "Foundation":
        parts = parts[:1]
        answers = answers[:1]
        steps = steps[:3]
        marks = 3
    elif difficulty == "Challenge":
        parts.append("(c) Verify the result using a closed triangle of forces.")
        marks = 8
    prompt = rf"""
A particle $P$ of weight ${weight}\,\mathrm{{N}}$ is attached to one end of a
light inextensible string. The other end is fixed at $O$. The string makes an
angle of ${beta}^\circ$ with the vertical. A force of magnitude $F\,\mathrm{{N}}$,
perpendicular to the string, holds $P$ in equilibrium.

{chr(10).join(parts)}
"""
    return Question(
        id=_qid("equilibrium", seed), seed=seed, topic="equilibrium",
        topic_label="Equilibrium · strings & forces", difficulty=difficulty,
        title="Force Prism", prompt=prompt, marks=marks,
        expected_answers=answers, solution_steps=steps,
        mark_scheme=[
            {"step": "Complete free-body diagram", "marks": 2},
            {"step": "Resolution perpendicular to string", "marks": 2},
            {"step": "Resolution along string", "marks": 2},
        ],
        theory_key="equilibrium",
        hints=[
            "Only three forces act on the particle: weight, tension and $F$.",
            "Choose axes along and perpendicular to the string.",
            r"The component of weight perpendicular to the string has magnitude $W\sin\beta$.",
        ],
        diagram_kind="equilibrium",
        diagram_data={"weight": weight, "beta": beta, "force": force, "tension": tension},
        common_errors=[
            {
                "value": weight * cos(radians(beta)),
                "title": "Sine and cosine components were interchanged",
                "explanation": r"$F$ is perpendicular to the string, so it balances the $W\sin\beta$ component; $T$ balances $W\cos\beta$.",
            }
        ],
    )


GENERATORS: dict[str, Callable[[random.Random, str, int], Question]] = {
    "vertical": _vertical,
    "speed_time": _speed_time,
    "collision": _collision,
    "beam": _beam,
    "friction": _friction,
    "connected": _connected,
    "vectors": _vectors,
    "equilibrium": _equilibrium,
}


def generate_question(
    topic_label: str = "Mixed mission",
    difficulty: str = "Exam standard",
    seed: int | str | None = None,
) -> dict[str, Any]:
    """Generate one reproducible, mathematically validated question."""
    if difficulty not in DIFFICULTIES:
        difficulty = "Exam standard"
    if seed in (None, ""):
        seed_int = int(time.time_ns() % 2_147_483_647)
    else:
        try:
            seed_int = int(seed)
        except (TypeError, ValueError):
            seed_int = sum((i + 1) * ord(ch) for i, ch in enumerate(str(seed)))
    rng = random.Random(seed_int)
    topic = TOPICS.get(topic_label, topic_label if topic_label in GENERATORS else "mixed")
    if topic == "mixed":
        topic = rng.choice(list(GENERATORS))
    return GENERATORS[topic](rng, difficulty, seed_int).to_dict()


def render_question(question: dict[str, Any]) -> str:
    """Render a clean exam-style card for Gradio Markdown."""
    if not question:
        return "Generate a mission to begin."
    return f"""
<div class="question-kicker">{question['topic_label']} · {question['difficulty']} · {question['marks']} marks</div>

## {question['title']}

{question['prompt'].strip()}

<div class="question-foot">Question ID: {question['id']} · Seed: {question['seed']} · Unofficial original practice content</div>
"""


def render_solution(question: dict[str, Any]) -> str:
    if not question:
        return "Generate a question first."
    answer_line = "  \n".join(
        f"- **{a['label']}:** {a['display']}" for a in question["expected_answers"]
    )
    steps = "\n".join(f"{i}. {step}" for i, step in enumerate(question["solution_steps"], 1))
    scheme = "\n".join(
        f"- {row['step']} — **{row['marks']} mark{'s' if row['marks'] != 1 else ''}**"
        for row in question["mark_scheme"]
    )
    return f"""
## Worked solution

{steps}

### Final answers

{answer_line}

### Mark-scheme map

{scheme}
"""