#!/usr/bin/env ts-node
import { gameDB } from "../routes/games/store";

type Args = {
  gameId?: string;
};

function parseArgs(): Args {
  const args = process.argv.slice(2);
  const res: Args = {};
  for (let i = 0; i < args.length; i++) {
    const a = args[i];
    if ((a === "-g" || a === "--game") && args[i + 1]) {
      res.gameId = String(args[i + 1]);
      i++;
    }
  }
  return res;
}

async function main() {
  const { gameId } = parseArgs();

  if (!gameDB.db) {
    await gameDB.init();
  }
  let db = gameDB.db;

  if (!db.sequelize) {
    console.error("DB does not expose sequelize; cannot run queries.");
    process.exit(1);
  }

  if (!gameId) {
    // List all game ids
    try {
      const rows: any[] = await db.sequelize.query("SELECT id, name FROM games", {
        type: db.Sequelize.QueryTypes.SELECT,
      });
      if (!rows || rows.length === 0) {
        console.log("No games found.");
        return;
      }
      console.log("Games:");
      rows.forEach((r) => console.log(`${r.id} - ${r.name}`));
    } catch (e) {
      console.error("Failed to list games:", e);
      process.exit(1);
    }
  } else {
    // For a given game ID, try to print the turns history from the state
    try {
      const rows: any[] = await db.sequelize.query("SELECT state FROM games WHERE id=:id", {
        replacements: { id: gameId },
        type: db.Sequelize.QueryTypes.SELECT,
      });
      if (!rows || rows.length === 0) {
        console.error("Game not found:", gameId);
        process.exit(2);
      }
      const r = rows[0] as any;
      let state = r.state;
      if (typeof state === "string") {
        try {
          state = JSON.parse(state);
        } catch (e) {
          console.error("Failed to parse stored state JSON:", e);
          process.exit(3);
        }
      }

      if (!state) {
        console.error("Empty state for game", gameId);
        process.exit(4);
      }

      console.log(`Game ${gameId} summary:`);
      console.log(` - turns: ${state.turns || 0}`);
      if (state.turnHistory || state.turnsData || state.turns_list) {
        const turns = state.turnHistory || state.turnsData || state.turns_list;
        console.log("Turns:");
        turns.forEach((t: any, idx: number) => {
          console.log(`${idx}: ${JSON.stringify(t)}`);
        });
      } else if (state.turns && state.turns > 0) {
        console.log("No explicit turn history found inside state; showing snapshot metadata.");
        // Print limited snapshot details per turn if available
        if (state.turnsData) {
          state.turnsData.forEach((t: any, idx: number) => console.log(`${idx}: ${JSON.stringify(t)}`));
        }
      } else {
        console.log("No turn history recorded in state.");
      }
    } catch (e) {
      console.error("Failed to load game state for", gameId, e);
      process.exit(1);
    }
  }
}

main();
