#!/usr/bin/env node
/**
 * Extracts Real Madrid and Barcelona squad data from the TouchLines game's
 * src/Data/squads/la_liga/ into typed slices the promo composition can
 * import. Re-runnable any time the game data changes.
 *
 * Output: promo-video/src/data/clubs.ts
 *
 * Usage:  node scripts/extract-club-data.mjs
 */

import { readFileSync, writeFileSync, copyFileSync, mkdirSync, existsSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = dirname(fileURLToPath(import.meta.url));
const PROMO_ROOT = resolve(__dirname, "..");
const GAME_ROOT = resolve(__dirname, "../../");

const SQUAD_DIR = join(GAME_ROOT, "src/Data/squads/la_liga");
const LOGO_SRC_DIR = join(GAME_ROOT, "src/Data/logos/la_liga");
const LOGO_DEST_DIR = join(PROMO_ROOT, "public/logos/la_liga");
const OUT_FILE = join(PROMO_ROOT, "src/data/clubs.ts");

/**
 * Composite rating ≈ mean of the 8 outfield attributes that matter most.
 * Mirrors the game's roster-level "headline rating" (not the per-match rating).
 */
function compositeRating(p) {
  const s = p.stats;
  // Goalkeepers: special blend (reflex / jump / strength + passing + positioning).
  if (p.positions?.[0] === "GK") {
    return (s.reflex * 2 + s.jump + s.strength + s.passing + s.pressing) / 6;
  }
  const v =
    s.passing +
    s.vision +
    s.finishing +
    s.dribbling +
    s.speed +
    s.acceleration +
    s.tackling +
    s.pressing;
  return v / 8;
}

function loadClub(file) {
  const raw = JSON.parse(readFileSync(join(SQUAD_DIR, file), "utf8"));
  return {
    id: raw.id,
    slug: raw.slug,
    name: raw.name,
    code: raw.code,
    colors: raw.colors,
    logo: raw.logo,
    founded: raw.founded,
    country: raw.country,
    venue: raw.venue,
    coach: raw.coach,
    players: raw.players.map((p) => ({
      id: p.id,
      name: p.name,
      fullName: p.fullName,
      age: p.age,
      preferredFoot: p.preferredFoot,
      positions: p.positions,
      stats: p.stats,
      profile: p.profile,
      rating: Math.round(compositeRating(p) * 10) / 10,
    })),
  };
}

function pickByRole(players, mainRole, count = 1) {
  return players
    .filter((p) => p.positions[0] === mainRole)
    .sort((a, b) => b.rating - a.rating)
    .slice(0, count);
}

/**
 * Build a believable 4-3-3 starting XI by composite rating per role.
 * Returns players annotated with their formation slot.
 */
function buildXI(players) {
  const gk = pickByRole(players, "GK", 1);
  const def = pickByRole(players, "Defender", 4);
  const mid = pickByRole(players, "Midfielder", 3);
  const fwd = pickByRole(players, "Forward", 3);

  // Engine yard coordinates (115 × 74 pitch).
  const slots = [
    { role: "GK", x: 5, y: 37 },
    { role: "LB", x: 18, y: 11 },
    { role: "CB", x: 22, y: 28 },
    { role: "CB", x: 22, y: 46 },
    { role: "RB", x: 18, y: 63 },
    { role: "CDM", x: 38, y: 37 },
    { role: "CM", x: 50, y: 24 },
    { role: "CM", x: 50, y: 50 },
    { role: "LW", x: 70, y: 8 },
    { role: "ST", x: 80, y: 37 },
    { role: "RW", x: 70, y: 66 },
  ];

  const lineup = [...gk, ...def, ...mid, ...fwd].slice(0, 11);
  return lineup.map((p, i) => ({ ...p, slot: slots[i] }));
}

function copyLogos(clubs) {
  if (!existsSync(LOGO_DEST_DIR)) mkdirSync(LOGO_DEST_DIR, { recursive: true });
  for (const c of clubs) {
    const filename = c.logo.split("/").pop();
    const from = join(LOGO_SRC_DIR, filename);
    const to = join(LOGO_DEST_DIR, filename);
    copyFileSync(from, to);
    console.log(`  logo  ${filename}`);
  }
}

const realMadrid = loadClub("541.json");
const barcelona = loadClub("529.json");

const rmXI = buildXI(realMadrid.players);
const bcXI = buildXI(barcelona.players);

// Bench: next 7 by rating, excluding XI.
const rmIds = new Set(rmXI.map((p) => p.id));
const rmBench = realMadrid.players
  .filter((p) => !rmIds.has(p.id))
  .sort((a, b) => b.rating - a.rating)
  .slice(0, 7);

const out = `// AUTO-GENERATED by scripts/extract-club-data.mjs
// Source: TouchLines src/Data/squads/la_liga/{541,529}.json
// Do not edit by hand — re-run the script when the game data changes.

export interface PlayerStats {
  passing: number; vision: number; finishing: number; dribbling: number;
  speed: number; acceleration: number; tackling: number; pressing: number;
  stamina: number; heading: number; strength: number;
  reflex: number; jump: number;
}

export interface ClubPlayer {
  id: string;
  name: string;
  fullName: string;
  age: number;
  preferredFoot: "left" | "right";
  positions: string[];
  stats: PlayerStats;
  profile: { summary: string; archetype: string };
  rating: number;
  slot?: { role: string; x: number; y: number };
}

export interface ClubVenue {
  name: string;
  city: string;
  capacity: number;
  surface: string;
}

export interface Club {
  id: string;
  slug: string;
  name: string;
  code: string;
  colors: [string, string];
  logo: string;          // relative to /public
  founded: number;
  country: string;
  venue: ClubVenue;
  coach: { id: number; name: string };
  starting11: ClubPlayer[];
  bench: ClubPlayer[];
}

export const REAL_MADRID: Club = ${JSON.stringify(
  {
    id: realMadrid.id,
    slug: realMadrid.slug,
    name: realMadrid.name,
    code: realMadrid.code,
    colors: realMadrid.colors,
    logo: realMadrid.logo,
    founded: realMadrid.founded,
    country: realMadrid.country,
    venue: realMadrid.venue,
    coach: { id: realMadrid.coach.id, name: realMadrid.coach.name },
    starting11: rmXI,
    bench: rmBench,
  },
  null,
  2,
)};

export const BARCELONA: Club = ${JSON.stringify(
  {
    id: barcelona.id,
    slug: barcelona.slug,
    name: barcelona.name,
    code: barcelona.code,
    colors: barcelona.colors,
    logo: barcelona.logo,
    founded: barcelona.founded,
    country: barcelona.country,
    venue: barcelona.venue,
    coach: { id: barcelona.coach.id, name: barcelona.coach.name },
    starting11: bcXI,
    bench: [],
  },
  null,
  2,
)};
`;

writeFileSync(OUT_FILE, out, "utf8");
copyLogos([realMadrid, barcelona]);

console.log("");
console.log(`✓ Wrote ${OUT_FILE}`);
console.log(`✓ Real Madrid XI: ${rmXI.map((p) => p.name).join(", ")}`);
console.log(`✓ Barcelona XI:   ${bcXI.map((p) => p.name).join(", ")}`);
