tcg_db 0.1.0

Pokemon TCG game engine database and card metadata
Documentation
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
use rusqlite::{params, Connection};
use serde_json::Value;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};

const SET_CODE: &str = "DF";
const CRITICAL_TRAINERS: &[&str] = &[
    "DF-72",
    "DF-75", // Holon Mentor
    "DF-79",
    "DF-80", // Professor Oak's Research
    "DF-82",
];

fn load_jsonl(path: &str) -> Result<HashMap<String, String>, String> {
    let file = File::open(path).map_err(|err| format!("Failed to open {path}: {err}"))?;
    let reader = BufReader::new(file);
    let mut cards = HashMap::new();
    for (index, line) in reader.lines().enumerate() {
        let line = line.map_err(|err| format!("Failed to read line {index}: {err}"))?;
        if line.trim().is_empty() {
            continue;
        }
        let value: Value = serde_json::from_str(&line)
            .map_err(|err| format!("Invalid JSON line {index}: {err}"))?;
        let number = value
            .get("number")
            .and_then(Value::as_str)
            .ok_or_else(|| format!("Missing number in line {index}"))?;
        let name = value
            .get("name")
            .and_then(Value::as_str)
            .ok_or_else(|| format!("Missing name in line {index}"))?;
        let name = normalize_name(name);
        let def_id = format!("{SET_CODE}-{number}");
        cards.insert(def_id, name.to_string());
    }
    Ok(cards)
}

fn load_jsonl_cards(path: &str) -> Result<Vec<Value>, String> {
    let file = File::open(path).map_err(|err| format!("Failed to open {path}: {err}"))?;
    let reader = BufReader::new(file);
    let mut cards = Vec::new();
    for (index, line) in reader.lines().enumerate() {
        let line = line.map_err(|err| format!("Failed to read line {index}: {err}"))?;
        if line.trim().is_empty() {
            continue;
        }
        let value: Value = serde_json::from_str(&line)
            .map_err(|err| format!("Invalid JSON line {index}: {err}"))?;
        cards.push(value);
    }
    Ok(cards)
}

fn effect_is_noop(effect: &str) -> bool {
    let value: Value = match serde_json::from_str(effect) {
        Ok(value) => value,
        Err(_) => return false,
    };
    value
        .get("op")
        .and_then(Value::as_str)
        .map(|op| op == "NoOp")
        .unwrap_or(false)
}

fn validate_non_noop_effects(conn: &Connection, cards: &[Value]) -> Result<(), String> {
    for card in cards {
        let number = card
            .get("number")
            .and_then(Value::as_str)
            .ok_or("Missing number in card JSON")?;
        let def_id = format!("{SET_CODE}-{number}");
        let supertype = card
            .get("supertype")
            .and_then(Value::as_str)
            .unwrap_or("Trainer");

        if supertype == "Pokémon" || supertype == "Pokemon" {
            if let Some(attacks) = card.get("attacks").and_then(Value::as_array) {
                for attack in attacks {
                    let text = attack.get("text").and_then(Value::as_str).unwrap_or("").trim();
                    if text.is_empty() {
                        continue;
                    }
                    let name = attack
                        .get("name")
                        .and_then(Value::as_str)
                        .ok_or("Missing attack name")?;
                    let effect: String = conn
                        .query_row(
                            "SELECT effect_ast FROM attacks WHERE card_def_id = ? AND name = ?",
                            params![def_id, name],
                            |row| row.get(0),
                        )
                        .map_err(|err| format!("Missing attack {def_id} {name}: {err}"))?;
                    if effect_is_noop(&effect) {
                        return Err(format!(
                            "Attack {def_id} {name} has text but still NoOp effect_ast."
                        ));
                    }
                }
            }
            if let Some(powers) = card.get("abilities").and_then(Value::as_array) {
                for power in powers {
                    let name = power
                        .get("name")
                        .and_then(Value::as_str)
                        .ok_or("Missing power name")?;
                    let effect: String = conn
                        .query_row(
                            "SELECT effect_ast FROM powers WHERE card_def_id = ? AND name = ?",
                            params![def_id, name],
                            |row| row.get(0),
                        )
                        .map_err(|err| format!("Missing power {def_id} {name}: {err}"))?;
                    if effect_is_noop(&effect) {
                        return Err(format!(
                            "Power {def_id} {name} has text but still NoOp effect_ast."
                        ));
                    }
                }
            }
        } else if supertype == "Trainer" {
            let effect: String = conn
                .query_row(
                    "SELECT script_payload FROM cards WHERE card_def_id = ?",
                    params![def_id],
                    |row| row.get(0),
                )
                .map_err(|err| format!("Missing trainer {def_id}: {err}"))?;
            if effect_is_noop(&effect) {
                return Err(format!(
                    "Trainer {def_id} has rules text but still NoOp effect_ast."
                ));
            }
        }
    }
    Ok(())
}

fn main() -> Result<(), String> {
    let args: Vec<String> = env::args().collect();
    if args.len() != 3 {
        return Err(format!("Usage: {} <db_path> <df_jsonl>", args[0]));
    }
    let db_path = &args[1];
    let jsonl_path = &args[2];

    let conn = Connection::open(db_path).map_err(|err| err.to_string())?;
    let expected = load_jsonl(jsonl_path)?;
    let cards = load_jsonl_cards(jsonl_path)?;

    let mut stmt = conn
        .prepare("SELECT card_def_id, name FROM cards WHERE card_def_id LIKE ?")
        .map_err(|err| err.to_string())?;
    let mut rows = stmt
        .query(params![format!("{SET_CODE}-%")])
        .map_err(|err| err.to_string())?;
    let mut found = HashMap::new();
    while let Some(row) = rows.next().map_err(|err| err.to_string())? {
        let def_id: String = row.get(0).map_err(|err| err.to_string())?;
        let name: String = row.get(1).map_err(|err| err.to_string())?;
        found.insert(def_id, normalize_name(&name));
    }

    let mut missing = Vec::new();
    let mut name_mismatch = Vec::new();
    for (def_id, name) in expected.iter() {
        match found.get(def_id) {
            None => missing.push(def_id.clone()),
            Some(db_name) if db_name != name => {
                name_mismatch.push((def_id.clone(), name.clone(), db_name.clone()));
            }
            _ => {}
        }
    }

    if !missing.is_empty() {
        return Err(format!("Missing {SET_CODE} cards in DB: {missing:?}"));
    }
    if !name_mismatch.is_empty() {
        return Err(format!(
            "Name mismatches for {SET_CODE}: {name_mismatch:?}"
        ));
    }

    for def_id in CRITICAL_TRAINERS {
        let payload: String = conn
            .query_row(
                "SELECT script_payload FROM cards WHERE card_def_id = ?",
                params![def_id],
                |row| row.get(0),
            )
            .map_err(|err| format!("Missing {def_id}: {err}"))?;
        if payload.contains("NoOp") {
            return Err(format!("Trainer {def_id} still has NoOp script_payload."));
        }
    }

    expect_attack_effect(
        &conn,
        "DF-2",
        "Drag Off",
        serde_json::json!({
            "op": "ChoosePokemonTargets",
            "player": "Current",
            "selector": {
                "scope": "OppBench"
            },
            "min": 1,
            "max": 1,
            "effect": {
                "op": "SwitchToTarget",
                "player": "Opponent"
            },
            "notes": "DF-2:Drag Off"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-12",
        "Burning Ball",
        serde_json::json!({
            "op": "ApplySpecialConditionIfEnergyAttached",
            "target": "OppActive",
            "energy_type": "Fire",
            "count": 2,
            "condition": "Burned",
            "notes": "DF-12:Burning Ball"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-13",
        "Burning Venom",
        serde_json::json!({
            "op": "Sequence",
            "effects": [
                { "op": "ApplySpecialCondition", "target": "OppActive", "condition": "Burned" },
                { "op": "ApplySpecialCondition", "target": "OppActive", "condition": "Poisoned" }
            ],
            "notes": "DF-13:Burning Venom"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-13",
        "Strangle",
        serde_json::json!({
            "op": "DealDamageIfTargetDelta",
            "target": "OppActive",
            "amount": 30,
            "notes": "DF-13:Strangle"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-14",
        "Grind",
        serde_json::json!({
            "op": "DealDamageByAttachedEnergy",
            "target": "OppActive",
            "per_energy": 10,
            "notes": "DF-14:Grind"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-19",
        "Lap Up",
        serde_json::json!({
            "op": "DrawCards",
            "player": "Current",
            "count": 2,
            "notes": "DF-19:Lap Up"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-19",
        "Delta Mind",
        serde_json::json!({
            "op": "ChoosePokemonTargets",
            "player": "Current",
            "selector": {
                "scope": "OppAll"
            },
            "min": 1,
            "max": 1,
            "effect": {
                "op": "PlaceDamageCountersIfTargetDelta",
                "target": "Selected",
                "base": 1,
                "delta": 3
            },
            "notes": "DF-19:Delta Mind"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-20",
        "Spiral Drain",
        serde_json::json!({
            "op": "HealDamage",
            "target": "SelfActive",
            "amount": 10,
            "notes": "DF-20:Spiral Drain"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-22",
        "Smokescreen",
        serde_json::json!({
            "op": "AddMarker",
            "target": "OppActive",
            "name": "Smokescreen",
            "expires_after_turns": 1,
            "notes": "DF-22:Smokescreen"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-24",
        "Quick Blow",
        serde_json::json!({
            "op": "FlipCoins",
            "count": 1,
            "on_heads": { "op": "DealDamage", "target": "OppActive", "amount": 20 },
            "on_tails": { "op": "NoOp" },
            "notes": "DF-24:Quick Blow"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-27",
        "Scary Face",
        serde_json::json!({
            "op": "FlipCoins",
            "count": 1,
            "on_heads": {
                "op": "Sequence",
                "effects": [
                    { "op": "AddMarker", "target": "OppActive", "name": "CannotAttack", "expires_after_turns": 1 },
                    { "op": "AddMarker", "target": "OppActive", "name": "CannotRetreat", "expires_after_turns": 1 }
                ]
            },
            "on_tails": { "op": "NoOp" },
            "notes": "DF-27:Scary Face"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-33",
        "Flickering Flames",
        serde_json::json!({
            "op": "ApplySpecialCondition",
            "target": "OppActive",
            "condition": "Asleep",
            "notes": "DF-33:Flickering Flames"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-36",
        "Quick Attack",
        serde_json::json!({
            "op": "FlipCoins",
            "count": 1,
            "on_heads": { "op": "DealDamage", "target": "OppActive", "amount": 20 },
            "on_tails": { "op": "NoOp" },
            "notes": "DF-36:Quick Attack"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-45",
        "Swift",
        serde_json::json!({
            "op": "DealDamageNoModifiers",
            "target": "OppActive",
            "amount": 30,
            "notes": "DF-45:Swift"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-50",
        "Sleepy Ball",
        serde_json::json!({
            "op": "ApplySpecialCondition",
            "target": "OppActive",
            "condition": "Asleep",
            "notes": "DF-50:Sleepy Ball"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-52",
        "Paralyzing Gaze",
        serde_json::json!({
            "op": "FlipCoins",
            "count": 1,
            "on_heads": {
                "op": "ApplySpecialCondition",
                "target": "OppActive",
                "condition": "Paralyzed"
            },
            "on_tails": { "op": "NoOp" },
            "notes": "DF-52:Paralyzing Gaze"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-59",
        "Hyper Beam",
        serde_json::json!({
            "op": "FlipCoins",
            "count": 1,
            "on_heads": { "op": "DiscardAttachedEnergy", "target": "OppActive", "count": 1 },
            "on_tails": { "op": "NoOp" },
            "notes": "DF-59:Hyper Beam"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-61",
        "Calm Mind",
        serde_json::json!({
            "op": "HealDamage",
            "target": "SelfActive",
            "amount": 20,
            "notes": "DF-61:Calm Mind"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-63",
        "Shell Grab",
        serde_json::json!({
            "op": "FlipCoins",
            "count": 1,
            "on_heads": {
                "op": "ApplySpecialCondition",
                "target": "OppActive",
                "condition": "Paralyzed"
            },
            "on_tails": { "op": "NoOp" },
            "notes": "DF-63:Shell Grab"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-67",
        "Rage",
        serde_json::json!({
            "op": "DealDamageByAttackerDamage",
            "target": "OppActive",
            "base": 10,
            "per_counter": 10,
            "notes": "DF-67:Rage"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-70",
        "Hypnotic Gaze",
        serde_json::json!({
            "op": "ApplySpecialCondition",
            "target": "OppActive",
            "condition": "Asleep",
            "notes": "DF-70:Hypnotic Gaze"
        }),
    )?;

    // Sceptile deck attacks
    expect_attack_effect(
        &conn,
        "DF-3",
        "Dig Deep",
        serde_json::json!({
            "op": "SearchDiscardWithSelector",
            "player": "Current",
            "selector": { "is_energy": true },
            "count": 1,
            "min": 0,
            "max": 1,
            "destination": "Hand",
            "notes": "DF-3:Dig Deep"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-3",
        "Extra Claws",
        serde_json::json!({
            "op": "Custom",
            "id": "DF-3:Extra Claws",
            "set": "DF",
            "notes": "30 damage + 20 if target is Pokemon-ex"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "DF-93",
        "Flame Ball",
        serde_json::json!({
            "op": "MoveAttachedEnergy",
            "source": "SelfActive",
            "target_selector": { "is_active": false },
            "energy_type": "Fire",
            "count": 1,
            "min": 0,
            "optional": true
        }),
    )?;

    expect_power_effect(
        &conn,
        "DF-2",
        "Battle Aura",
        serde_json::json!({
            "op": "Custom",
            "id": "DF-2:Battle Aura",
            "set": "DF",
            "kind": "PokeBody",
            "name": "Battle Aura",
            "card": "Feraligatr Delta",
            "notes": "Your Delta Pokemon attacks do +10 damage."
        }),
    )?;
    expect_power_effect(
        &conn,
        "DF-12",
        "Shady Move",
        serde_json::json!({
            "op": "Custom",
            "id": "DF-12:Shady Move",
            "set": "DF",
            "kind": "PokePower",
            "name": "Shady Move",
            "card": "Typhlosion Delta",
            "notes": "Active only; move 1 counter between any Pokemon."
        }),
    )?;
    expect_power_effect(
        &conn,
        "DF-14",
        "Solid Shell",
        serde_json::json!({
            "op": "Custom",
            "id": "DF-14:Solid Shell",
            "set": "DF",
            "kind": "PokeBody",
            "name": "Solid Shell",
            "card": "Cloyster Delta",
            "notes": "Prevent effects of attacks to your Benched Delta Pokemon."
        }),
    )?;
    expect_power_effect(
        &conn,
        "DF-20",
        "Power Circulation",
        serde_json::json!({
            "op": "Custom",
            "id": "DF-20:Power Circulation",
            "set": "DF",
            "kind": "PokePower",
            "name": "Power Circulation",
            "card": "Mantine Delta",
            "notes": "Put basic Energy from discard on top of deck, then damage self."
        }),
    )?;
    expect_power_effect(
        &conn,
        "DF-24",
        "Psychic Wing",
        serde_json::json!({
            "op": "Custom",
            "id": "DF-24:Psychic Wing",
            "set": "DF",
            "kind": "PokeBody",
            "name": "Psychic Wing",
            "card": "Vibrava Delta",
            "notes": "If Psychic Energy attached, retreat cost is 0."
        }),
    )?;

    // Trainer effect validations
    expect_trainer_effect(
        &conn,
        "DF-75",
        serde_json::json!({
            "op": "IfHandNotEmpty",
            "player": "Current",
            "effect": {
                "op": "Sequence",
                "effects": [
                    { "op": "DiscardFromHand", "player": "Current", "count": 1 },
                    {
                        "op": "SearchDeckWithSelector",
                        "player": "Current",
                        "selector": { "is_basic": true, "is_pokemon": true, "max_hp": 100 },
                        "min": 0,
                        "max": 3,
                        "count": 3,
                        "destination": "Hand",
                        "reveal": true,
                        "shuffle": true
                    }
                ]
            },
            "notes": "DF-75:Holon Mentor"
        }),
    )?;
    expect_trainer_effect(
        &conn,
        "DF-80",
        serde_json::json!({
            "op": "Sequence",
            "effects": [
                { "op": "ShuffleHandIntoDeck", "player": "Current" },
                { "op": "DrawCards", "player": "Current", "count": 5 }
            ],
            "notes": "DF-80:Professor Oaks Research"
        }),
    )?;

    let energy_count: i64 = conn
        .query_row(
            "SELECT count(*) FROM cards WHERE card_def_id = 'ENERGY-GRASS'",
            [],
            |row| row.get(0),
        )
        .map_err(|err| err.to_string())?;
    if energy_count != 1 {
        return Err("ENERGY-GRASS missing from DB.".to_string());
    }

    validate_non_noop_effects(&conn, &cards)?;

    println!("DF card validation passed.");
    Ok(())
}

fn normalize_name(name: &str) -> String {
    let normalized = name
        .replace('δ', "Delta")
        .replace("Pokémon", "Pokemon")
        .replace('é', "e");
    normalized
        .trim()
        .strip_suffix(" Delta")
        .unwrap_or(normalized.trim())
        .to_string()
}

fn expect_attack_effect(
    conn: &Connection,
    def_id: &str,
    attack_name: &str,
    expected: Value,
) -> Result<(), String> {
    let effect: String = conn
        .query_row(
            "SELECT effect_ast FROM attacks WHERE card_def_id = ? AND name = ?",
            params![def_id, attack_name],
            |row| row.get(0),
        )
        .map_err(|err| format!("Missing attack {def_id} {attack_name}: {err}"))?;
    let value: Value =
        serde_json::from_str(&effect).map_err(|err| format!("{def_id} {attack_name} invalid JSON: {err}"))?;
    if value != expected {
        return Err(format!(
            "{def_id} {attack_name} effect_ast mismatch. expected={expected} actual={value}"
        ));
    }
    Ok(())
}

fn expect_power_effect(
    conn: &Connection,
    def_id: &str,
    power_name: &str,
    expected: Value,
) -> Result<(), String> {
    let effect: String = conn
        .query_row(
            "SELECT effect_ast FROM powers WHERE card_def_id = ? AND name = ?",
            params![def_id, power_name],
            |row| row.get(0),
        )
        .map_err(|err| format!("Missing power {def_id} {power_name}: {err}"))?;
    let value: Value =
        serde_json::from_str(&effect).map_err(|err| format!("{def_id} {power_name} invalid JSON: {err}"))?;
    if value != expected {
        return Err(format!(
            "{def_id} {power_name} effect_ast mismatch. expected={expected} actual={value}"
        ));
    }
    Ok(())
}

fn expect_trainer_effect(conn: &Connection, def_id: &str, expected: Value) -> Result<(), String> {
    let effect: String = conn
        .query_row(
            "SELECT script_payload FROM cards WHERE card_def_id = ?",
            params![def_id],
            |row| row.get(0),
        )
        .map_err(|err| format!("Missing trainer {def_id}: {err}"))?;
    let value: Value =
        serde_json::from_str(&effect).map_err(|err| format!("{def_id} invalid JSON: {err}"))?;
    if value != expected {
        return Err(format!(
            "{def_id} script_payload mismatch.\nexpected={expected}\nactual={value}"
        ));
    }
    Ok(())
}