import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const CATEGORIES = [
  { slug: "arcade", name: "Arcade", blurb: "Fast, classic pick-up-and-play action." },
  { slug: "puzzle", name: "Puzzle", blurb: "Brain-teasers, logic and clever mechanics." },
  { slug: "racing", name: "Racing", blurb: "Speed, drifts and photo finishes." },
  { slug: "sports", name: "Sports", blurb: "Kick, shoot, swing and score." },
  { slug: "action", name: "Action", blurb: "Reflexes, combat and high energy." },
  { slug: "strategy", name: "Strategy", blurb: "Plan ahead and outsmart the odds." },
  { slug: "brain", name: "Brain", blurb: "Memory, focus and mental workouts." },
  { slug: "adventure", name: "Adventure", blurb: "Explore worlds and follow the story." },
  { slug: "casual", name: "Casual", blurb: "Relaxed games for short breaks." },
  { slug: "multiplayer", name: "Multiplayer", blurb: "Play with or against friends." },
] as const;

interface SeedGame {
  slug: string;
  title: string;
  description: string;
  category: string;
  developer: string;
  status?: "draft" | "published" | "disabled";
  featured?: boolean;
  trending?: boolean;
  instructions: string;
  controls: string;
  /** Demo embed source. Only used together with the embed allowlist. */
  embedUrl?: string;
  /** Real official/source URL. Overrides the demo example.com default. */
  officialUrl?: string;
}

/**
 * All records below are clearly fictional demo entries created for
 * development. Descriptions are original placeholder copy — no third-party
 * assets, text, or game files are used.
 */
const GAMES: SeedGame[] = [
  {
    slug: "neon-racer",
    title: "Neon Racer",
    description:
      "A fictional demo racing game. Weave a light-trail hover car through glowing night circuits and beat your own best lap.",
    category: "racing",
    developer: "Demo Works",
    featured: true,
    trending: true,
    instructions:
      "Finish 3 laps as fast as you can. Avoid barriers — each hit costs you speed.",
    controls: "Arrow keys or WASD to steer and accelerate. R resets the run.",
  },
  {
    slug: "starfall-puzzles",
    title: "Starfall Puzzles",
    description:
      "A fictional demo puzzle game. Slide falling star tiles into constellations to clear the night sky, one pattern at a time.",
    category: "puzzle",
    developer: "Demo Works",
    featured: true,
    instructions:
      "Complete the target constellation in as few moves as possible. Unused stars carry over as bonus points.",
    controls: "Click or tap a tile to select it, then click a highlighted slot to place it.",
  },
  {
    slug: "dungeon-delvers",
    title: "Dungeon Delvers",
    description:
      "A fictional demo adventure game. Explore a tiny torch-lit dungeon, collect keys, and find the exit on every floor.",
    category: "adventure",
    developer: "Paper Lantern Dev",
    trending: true,
    instructions:
      "Find the brass key on each floor to unlock the stairs down. Torches refill your light meter.",
    controls: "Arrow keys or WASD to move. E interacts with doors and chests.",
  },
  {
    slug: "quick-kick",
    title: "Quick Kick",
    description:
      "A fictional demo sports game. Time your shots and bend free kicks past the wall in a 60-second shootout.",
    category: "sports",
    developer: "Paper Lantern Dev",
    instructions:
      "Score as many goals as you can in 60 seconds. Swerving shots earn style bonuses.",
    controls: "Drag to aim, release to shoot. Move the mouse while the ball flies to swerve it.",
  },
  {
    slug: "blade-arena",
    title: "Blade Arena",
    description:
      "A fictional demo action game. Face waves of training bots in a circular arena and chain dodges for combo multipliers.",
    category: "action",
    developer: "Northbyte Studio",
    trending: true,
    instructions:
      "Survive 10 waves. Dodging at the last moment doubles your combo for 5 seconds.",
    controls: "WASD to move, Space to dodge, J or click to attack.",
  },
  {
    slug: "tiny-tactics",
    title: "Tiny Tactics",
    description:
      "A fictional demo strategy game. Command a squad of pocket knights across grid battlefields and outflank the rival banner.",
    category: "strategy",
    developer: "Northbyte Studio",
    instructions:
      "Capture the rival banner in under 12 turns. High ground gives ranged units extra damage.",
    controls: "Click a unit, then click a highlighted tile to move or attack. End turn with the button or Enter.",
  },
  {
    slug: "memory-meadows",
    title: "Memory Meadows",
    description:
      "A fictional demo brain game. Watch fireflies light up in sequence, then repeat the pattern as the meadow grows darker.",
    category: "brain",
    developer: "Demo Works",
    instructions:
      "Repeat the firefly sequence exactly. Each round adds one more light to remember.",
    controls: "Click or tap the flowers in the order they lit up.",
  },
  {
    slug: "pixel-pioneers",
    title: "Pixel Pioneers",
    description:
      "A fictional demo casual game. Build a cozy island settlement one plot at a time — no timers, no losing, just building.",
    category: "casual",
    developer: "Cozy Pixel Co.",
    featured: true,
    instructions:
      "Place houses, farms, and decorations to grow your island. Happy settlers unlock new buildings.",
    controls: "Click a plot to build. Drag with right-click held to pan the camera.",
  },
  {
    slug: "orbit-racers",
    title: "Orbit Racers",
    description:
      "A fictional demo multiplayer game. Race friends around a low-gravity ring station where every shortcut is a risk.",
    category: "multiplayer",
    developer: "Northbyte Studio",
    instructions:
      "Invite up to 5 friends to a lobby. First across the line after 3 laps wins the orbit crown.",
    controls: "Arrow keys or WASD to fly. Shift uses your picked-up boost item.",
  },
  {
    slug: "block-breaker-blitz",
    title: "Block Breaker Blitz",
    description:
      "A fictional demo arcade game. Bounce the energy ball, smash neon blocks, and catch falling power cores.",
    category: "arcade",
    developer: "Cozy Pixel Co.",
    instructions:
      "Clear all blocks to advance. Don't let the ball fall — you have 3 lives per stage.",
    controls: "Move the mouse or use Left/Right arrows to slide the paddle.",
    // Demo only: fictional embed source on the reserved example.com domain.
    embedUrl: "https://example.com/embed/block-breaker-blitz",
  },
  {
    slug: "ghost-circuit",
    title: "Ghost Circuit",
    description:
      "A fictional demo racing game (draft). This entry is intentionally unpublished to exercise draft-status filtering.",
    category: "racing",
    developer: "Demo Works",
    status: "draft",
    instructions: "Draft entry — instructions pending review.",
    controls: "Draft entry — controls pending review.",
  },
  {
    slug: "mythic-mines",
    title: "Mythic Mines",
    description:
      "A fictional demo strategy game (disabled). This entry is intentionally disabled to exercise disabled-status filtering.",
    category: "strategy",
    developer: "Northbyte Studio",
    status: "disabled",
    instructions: "Disabled entry — not shown publicly.",
    controls: "Disabled entry — not shown publicly.",
  },
];

/**
 * Verified real browser games (curated collection, added 2026-09-27).
 *
 * Each entry was verified against its source page before publishing:
 * title, genre/category, author and HTML5 browser playability confirmed.
 * Descriptions below are short original catalog summaries (not copied text).
 * All entries are EXTERNAL_LINK (embedAllowed: false, embedUrl: null) —
 * thumbnails use the site's generated placeholder art (no hotlinking).
 *
 * Deduplication applied at insert time:
 * - "15 Puzzle" was supplied twice → single record.
 * - CosmoKick was supplied under Sports/Action/Strategy → single record,
 *   primary category Sports (its itch.io genre; no tags architecture exists).
 * - The itch.io Casual listing page is a discovery page, not a game → skipped.
 * - PolyTrack kept in Multiplayer: server-based networked multiplayer is a
 *   documented feature (0.6.0) and "Multiplayer" is an official tag.
 * - "Midero" published under its actual page title "MiReDo".
 */
const REAL_GAMES: SeedGame[] = [
  {
    slug: "decanta-water-sort",
    title: "Decanta: Water Sort",
    description:
      "Pour and sort colored liquids between tubes until each tube holds a single color. A calm water-sort puzzler that runs in the browser.",
    category: "puzzle",
    developer: "alliterhorst",
    officialUrl: "https://alliterhorst.github.io/decanta-water-sort/",
    instructions:
      "Tap a tube, then tap another tube to pour. Finish with one color per tube to clear the level.",
    controls: "Click or tap tubes to select and pour.",
  },
  {
    slug: "unb1ok",
    title: "Unb1ok",
    description:
      "Slide the blocking pieces around the board to clear a path and guide the red block out through the exit.",
    category: "puzzle",
    developer: "vakuras",
    officialUrl: "https://vakuras.github.io/Unb1ok/",
    instructions:
      "Free the red block. Slide pieces out of the way level by level.",
    controls: "Click or tap and drag blocks to slide them.",
  },
  {
    slug: "15-puzzle",
    title: "15 Puzzle",
    description:
      "The classic sliding-tile puzzle: arrange the numbered tiles in order from 1 to 15. Open source (MIT) by Greg P.",
    category: "puzzle",
    developer: "Greg P.",
    officialUrl: "https://gregpuzzles1.github.io/15puzzle/",
    instructions:
      "Slide tiles into the empty space until all numbers read 1 to 15 in order.",
    controls: "Click a tile next to the empty space to slide it.",
  },
  {
    slug: "reach-that-point",
    title: "Reach That Point [LD48]",
    description:
      "A rope-physics puzzler from Ludum Dare 48: swing one end of the rope with your mouse and touch each point against the pull. Open source (MIT).",
    category: "puzzle",
    developer: "Dmitry Mozgin",
    officialUrl: "https://m039.itch.io/reach-that-point-ld48",
    instructions:
      "Guide the rope end to every target point without letting the pull drag you away.",
    controls: "Move the mouse to swing one end of the rope.",
  },
  {
    slug: "balckets",
    title: "Balckets",
    description:
      "Quick-fire math and logic challenges that train mental calculation and fast decisions. Open source (MIT) brain-training game.",
    category: "brain",
    developer: "ekomateas",
    officialUrl: "https://ekomateas.itch.io/balckets",
    instructions:
      "Solve the math and logic prompts as quickly and accurately as you can.",
    controls: "Playable with mouse or touch; see the source page for details.",
  },
  {
    slug: "memory-tile-quest-challenge",
    title: "Memory Tile Quest Challenge",
    description:
      "Flip tiles and match all pairs in as few moves as possible in this lightweight browser memory game. Open source (MIT).",
    category: "brain",
    developer: "Indie Neuron Studio",
    officialUrl:
      "https://indie-neuron-studio.itch.io/memory-tile-quest-challenge",
    instructions:
      "Memorize tile positions and clear the whole board with the fewest moves.",
    controls: "Click or tap tiles to flip them and find pairs.",
  },
  {
    slug: "midero",
    title: "MiReDo",
    description:
      "A rhythm memory game: watch notes play across eight pads, then repeat the sequence in reverse order. Open source (MIT).",
    category: "brain",
    developer: "BananaPants87, StarryBadger, Himanshu Yadav",
    officialUrl: "https://praneethjain.itch.io/midero",
    instructions:
      "Remember the note sequence, then play it back backwards. Sequences grow each level.",
    controls: "Click the pads (mouse or touch) to play notes.",
  },
  {
    slug: "stroop",
    title: "Stroop",
    description:
      "Match the ink color, not the written word, in this fast reaction game inspired by the Stroop effect.",
    category: "brain",
    developer: "Indifferent Penguin",
    officialUrl: "https://indifferentpenguin.itch.io/stroop",
    instructions:
      "Score by choosing the color of the ink while the words try to mislead you.",
    controls: "Use the keyboard arrows or the on-screen touch arrows.",
  },
  {
    slug: "vibe-weavers",
    title: "Vibe Weavers",
    description:
      "An open 3D browser racing and exploration playground with P2P multiplayer, built as a single HTML file. Open source (MIT).",
    category: "racing",
    developer: "leoawen",
    officialUrl: "https://leoawen.itch.io/vibe-weavers",
    instructions:
      "Drive, explore and create in the open 3D playground, solo or with others over P2P.",
    controls: "Keyboard driving controls; see the source page for details.",
  },
  {
    slug: "cosmokick",
    title: "CosmoKick",
    description:
      "Physics-based 3D browser football with fast online multiplayer matches. Free to play, no downloads.",
    category: "sports",
    developer: "CosmoKick",
    featured: true,
    instructions:
      "Outscore your opponents in fast physics-driven football matches, solo or online.",
    controls:
      "Keyboard and mouse, touch controls, or Xbox/PlayStation controller.",
    officialUrl: "https://cosmokick.itch.io/cosmokick",
  },
  {
    slug: "bots-n-bugs",
    title: "Bots n' Bugs",
    description:
      "Run, jump and stomp slimes, rats and spiders through a robot platform adventure to free Botsville. Made with Godot.",
    category: "adventure",
    developer: "Flashsloth",
    trending: true,
    officialUrl: "https://flashsloth.itch.io/bots-n-bugs",
    instructions:
      "Clear each level of creatures and touch the door to advance.",
    controls: "WASD or arrow keys to move. Stomp on enemies to defeat them.",
  },
  {
    slug: "polytrack",
    title: "PolyTrack",
    description:
      "Race the clock on low-poly tracks with loops and jumps, build your own in the level editor, and play online multiplayer.",
    category: "multiplayer",
    developer: "Kodub",
    featured: true,
    trending: true,
    officialUrl: "https://kodub.itch.io/polytrack",
    instructions:
      "Beat the clock on each track, or build and share your own in the editor.",
    controls: "WASD or arrow keys to drive. R or Enter restarts the track.",
  },
];

async function main() {
  for (const c of CATEGORIES) {
    await prisma.category.upsert({
      where: { slug: c.slug },
      update: { name: c.name, blurb: c.blurb },
      create: c,
    });
  }

  for (const g of [...GAMES, ...REAL_GAMES]) {
    const category = await prisma.category.findUniqueOrThrow({
      where: { slug: g.category },
    });
    const officialUrl =
      g.officialUrl ?? `https://example.com/games/${g.slug}`;
    await prisma.game.upsert({
      where: { slug: g.slug },
      update: {
        embedUrl: g.embedUrl ?? null,
        embedAllowed: Boolean(g.embedUrl),
      },
      create: {
        slug: g.slug,
        title: g.title,
        description: g.description,
        categoryId: category.id,
        developer: g.developer,
        publisher: null,
        officialUrl,
        sourceDomain: new URL(officialUrl).hostname,
        embedUrl: g.embedUrl ?? null,
        embedAllowed: Boolean(g.embedUrl),
        status: g.status ?? "published",
        featured: g.featured ?? false,
        trending: g.trending ?? false,
        instructions: g.instructions,
        controls: g.controls,
      },
    });
  }

  const [cats, games] = await Promise.all([
    prisma.category.count(),
    prisma.game.count(),
  ]);
  console.log(`Seed complete: ${cats} categories, ${games} games.`);
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(() => {
    void prisma.$disconnect();
  });
