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
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 = "CG";
const CRITICAL_TRAINERS: &[&str] = &[
    "CG-71",
    "CG-73",
    "CG-77",
    "CG-78",
    "CG-82",
    "CG-84", // Warp Point
    "CG-86",
    "CG-87",
];
// Critical attacks that must never be NoOp - these have complex effects that must be properly implemented
const CRITICAL_ATTACKS: &[(&str, &str)] = &[
    ("CG-28", "Toxic Sleep"), // Venusaur: Must apply Asleep+Poisoned and add marker for extra poison damage
];

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> <cg_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."));
        }
    }

    validate_non_noop_effects(&conn, &cards)?;

    // Validate critical attacks are never NoOp
    for (def_id, attack_name) in CRITICAL_ATTACKS {
        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}"))?;
        if effect.contains("\"op\":\"NoOp\"") || effect == "{\"op\":\"NoOp\"}" {
            return Err(format!(
                "Critical attack {def_id} {attack_name} still has NoOp effect_ast. This attack must have proper effect implementation."
            ));
        }
    }

    expect_attack_effect(
        &conn,
        "CG-23",
        "Surprise",
        serde_json::json!({
            "op": "ReturnRandomCardFromHandToDeck",
            "player": "Opponent",
            "reveal": true,
            "shuffle": true,
            "notes": "CG-23:Surprise"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "CG-23",
        "Bass Control",
        serde_json::json!({
            "op": "ChoosePokemonTargets",
            "player": "Current",
            "selector": {
                "scope": "OppAll"
            },
            "min": 1,
            "max": 1,
            "effect": {
                "op": "DealDamage",
                "target": "Selected",
                "amount": 40
            },
            "notes": "CG-23:Bass Control"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "CG-28",
        "Green Blast",
        serde_json::json!({
            "op": "DealDamageByEnergyInPlay",
            "player": "Current",
            "energy_type": "Grass",
            "target": "OppActive",
            "per_energy": 10,
            "notes": "CG-28:Green Blast"
        }),
    )?;
    // Venusaur (CG-28) "Toxic Sleep": Critical attack that must apply Asleep+Poisoned and add marker
    // for extra poison damage between turns. This is validated both here and in CRITICAL_ATTACKS above.
    expect_attack_effect(
        &conn,
        "CG-28",
        "Toxic Sleep",
        serde_json::json!({
            "op": "Sequence",
            "effects": [
                {
                    "op": "ApplySpecialCondition",
                    "target": "OppActive",
                    "condition": "Asleep"
                },
                {
                    "op": "ApplySpecialCondition",
                    "target": "OppActive",
                    "condition": "Poisoned"
                },
                {
                    "op": "AddMarker",
                    "target": "OppActive",
                    "name": "Toxic Sleep"
                }
            ],
            "notes": "CG-28:Toxic Sleep"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "CG-32",
        "Detect",
        serde_json::json!({
            "op": "FlipCoins",
            "count": 1,
            "on_heads": {
                "op": "AddMarker",
                "target": "SelfActive",
                "name": "Detect",
                "expires_after_turns": 1
            },
            "on_tails": { "op": "NoOp" },
            "notes": "CG-32:Detect"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "CG-33",
        "Amnesia",
        serde_json::json!({
            "op": "ChooseDefenderAttack",
            "target": "OppActive",
            "notes": "CG-33:Amnesia"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "CG-34",
        "Sleep Powder",
        serde_json::json!({
            "op": "ApplySpecialCondition",
            "target": "OppActive",
            "condition": "Asleep",
            "notes": "CG-34:Sleep Powder"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "CG-45",
        "Poisonpowder",
        serde_json::json!({
            "op": "ApplySpecialCondition",
            "target": "OppActive",
            "condition": "Poisoned",
            "notes": "CG-45:Poisonpowder"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "CG-53",
        "Hypnoblast",
        serde_json::json!({
            "op": "ApplySpecialCondition",
            "target": "OppActive",
            "condition": "Asleep",
            "notes": "CG-53:Hypnoblast"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "CG-67",
        "Paralyzing Gaze",
        serde_json::json!({
            "op": "FlipCoins",
            "count": 1,
            "on_heads": {
                "op": "ApplySpecialCondition",
                "target": "OppActive",
                "condition": "Paralyzed"
            },
            "on_tails": { "op": "NoOp" },
            "notes": "CG-67:Paralyzing Gaze"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "CG-69",
        "Supersonic",
        serde_json::json!({
            "op": "FlipCoins",
            "count": 1,
            "on_heads": {
                "op": "ApplySpecialCondition",
                "target": "OppActive",
                "condition": "Confused"
            },
            "on_tails": { "op": "NoOp" },
            "notes": "CG-69:Supersonic"
        }),
    )?;

    // Sceptile deck attacks
    expect_attack_effect(
        &conn,
        "CG-68",
        "Shining Claws",
        serde_json::json!({
            "op": "FlipCoins",
            "count": 1,
            "on_heads": { "op": "ApplySpecialCondition", "target": "OppActive", "condition": "Confused" },
            "on_tails": { "op": "NoOp" },
            "notes": "CG-68:Shining Claws"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "CG-19",
        "Agility",
        serde_json::json!({
            "op": "FlipCoins",
            "count": 1,
            "on_heads": { "op": "AddMarker", "target": "SelfActive", "name": "PreventAllDamageAndEffects", "expires_after_turns": 1 },
            "on_tails": { "op": "NoOp" },
            "notes": "CG-19:Agility"
        }),
    )?;
    expect_attack_effect(
        &conn,
        "CG-96",
        "Power Revenge",
        serde_json::json!({
            "op": "DealDamageByOpponentPrizesTaken",
            "target": "OppActive",
            "base": 60,
            "per_prize": 10,
            "notes": "CG-96:Power Revenge"
        }),
    )?;

    expect_power_effect(
        &conn,
        "CG-28",
        "Chlorophyll",
        serde_json::json!({
            "op": "Custom",
            "id": "CG-28:Chlorophyll",
            "set": "CG",
            "kind": "PokeBody",
            "name": "Chlorophyll",
            "card": "Venusaur",
            "notes": "Grass Pokemon treat Colorless Energy as Grass."
        }),
    )?;

    // Trainer effect validations
    expect_trainer_effect(
        &conn,
        "CG-84",
        serde_json::json!({
            "op": "Sequence",
            "effects": [
                {
                    "op": "ChoosePokemonTargets",
                    "player": "Opponent",
                    "selector": { "scope": "OppBench" },
                    "min": 1,
                    "max": 1,
                    "effect": { "op": "SwitchToTarget", "player": "Opponent" }
                },
                {
                    "op": "ChoosePokemonTargets",
                    "player": "Current",
                    "selector": { "scope": "SelfBench" },
                    "min": 1,
                    "max": 1,
                    "effect": { "op": "SwitchToTarget", "player": "Current" }
                }
            ],
            "notes": "CG-84:Warp Point"
        }),
    )?;

    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());
    }

    println!("CG 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(())
}