/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Database } from "bun:sqlite"; import { join } from "node:path"; import { existsSync } from "node:fs"; import type { BigDataStats, PlayerQueryFilter, PlayerRecord } from "./types.ts"; export class FutDatabaseRepository { private db: Database; private dbPath: string; constructor(customDbPath?: string) { const defaultPath = join(import.meta.dir, "../data/fut_extracted_database.sqlite"); const dbPath = customDbPath ?? defaultPath; if (!existsSync(dbPath)) { throw new Error(`FUT extracted database not found at: ${dbPath}`); } this.dbPath = dbPath; this.db = new Database(dbPath, { readonly: true }); } public getStats(): BigDataStats { const totalPlayers = (this.db.query("SELECT COUNT(*) as c FROM players").get() as any)?.c ?? 0; const totalClubs = (this.db.query("SELECT COUNT(DISTINCT club) as c FROM players WHERE club IS NOT NULL").get() as any)?.c ?? 0; const totalNations = (this.db.query("SELECT COUNT(DISTINCT nation) as c FROM players WHERE nation IS NOT NULL").get() as any)?.c ?? 0; const totalLeagues = (this.db.query("SELECT COUNT(DISTINCT league) as c FROM players WHERE league IS NOT NULL").get() as any)?.c ?? 0; const avgRating = (this.db.query("SELECT AVG(overall_rating) as a, MAX(overall_rating) as m FROM players").get() as any); const ratingRows = this.db.query(` SELECT CASE WHEN overall_rating >= 90 THEN '90+' WHEN overall_rating >= 85 THEN '85-89' WHEN overall_rating >= 80 THEN '80-84' WHEN overall_rating >= 75 THEN '75-79' WHEN overall_rating >= 65 THEN 'Silver (65-74)' ELSE 'Bronze (<65)' END as tier, COUNT(*) as count FROM players GROUP BY tier `).all() as any[]; const ratingDistribution: Record = {}; for (const r of ratingRows) { ratingDistribution[r.tier] = r.count; } const genderRows = this.db.query("SELECT gender, COUNT(*) as count FROM players GROUP BY gender").all() as any[]; const genderDistribution: Record = {}; for (const g of genderRows) { genderDistribution[g.gender || "Unknown"] = g.count; } return { totalPlayers, totalClubs, totalNations, totalLeagues, averageRating: Math.round((avgRating?.a ?? 0) * 10) / 10, maxRating: avgRating?.m ?? 0, topPlaystyles: [], ratingDistribution, genderDistribution, }; } public queryPlayers(filter: PlayerQueryFilter = {}): PlayerRecord[] { const clauses: string[] = ["1=1"]; const params: Record = {}; if (filter.name) { const clean = filter.name.trim(); const normalized = clean.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase(); const words = normalized.split(/[\s-]+/).filter((w) => w.length >= 3); const normSql = `REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(lower(name), 'é', 'e'), 'è', 'e'), 'ê', 'e'), 'ë', 'e'), 'á', 'a'), 'ã', 'a'), 'à', 'a'), 'â', 'a'), 'ç', 'c'), 'í', 'i'), 'ó', 'o'), 'õ', 'o')`; const nameConditions: string[] = [ "name LIKE $nameExact", `${normSql} LIKE $nameNorm`, "id LIKE $nameNorm", ]; params["$nameExact"] = `%${clean}%`; params["$nameNorm"] = `%${normalized}%`; if (words.length >= 2) { const first = words[0]; const last = words[words.length - 1]; nameConditions.push(`(${normSql} LIKE $wFirst AND ${normSql} LIKE $wLast)`); params["$wFirst"] = `%${first}%`; params["$wLast"] = `%${last}%`; if (words.length >= 3) { const second = words[1]; nameConditions.push(`(${normSql} LIKE $wFirst AND ${normSql} LIKE $wSecond)`); params["$wSecond"] = `%${second}%`; } } clauses.push(`(${nameConditions.join(" OR ")})`); } if (filter.position) { clauses.push("(position = $pos OR alternative_positions LIKE $posAlt)"); params["$pos"] = filter.position; params["$posAlt"] = `%${filter.position}%`; } if (filter.minRating !== undefined) { clauses.push("overall_rating >= $minRating"); params["$minRating"] = filter.minRating; } if (filter.maxRating !== undefined) { clauses.push("overall_rating <= $maxRating"); params["$maxRating"] = filter.maxRating; } if (filter.league) { clauses.push("league = $league"); params["$league"] = filter.league; } if (filter.nation) { clauses.push("nation = $nation"); params["$nation"] = filter.nation; } if (filter.club) { clauses.push("club = $club"); params["$club"] = filter.club; } if (filter.gender) { clauses.push("gender = $gender"); params["$gender"] = filter.gender; } if (filter.minPace !== undefined) { clauses.push("pac >= $minPace"); params["$minPace"] = filter.minPace; } if (filter.minShooting !== undefined) { clauses.push("sho >= $minShooting"); params["$minShooting"] = filter.minShooting; } if (filter.minPassing !== undefined) { clauses.push("pas >= $minPassing"); params["$minPassing"] = filter.minPassing; } if (filter.minDribbling !== undefined) { clauses.push("dri >= $minDribbling"); params["$minDribbling"] = filter.minDribbling; } if (filter.minDefending !== undefined) { clauses.push("def >= $minDefending"); params["$minDefending"] = filter.minDefending; } if (filter.minPhysical !== undefined) { clauses.push("phy >= $minPhysical"); params["$minPhysical"] = filter.minPhysical; } if (filter.playstyles && filter.playstyles.length > 0) { for (let i = 0; i < filter.playstyles.length; i++) { const ps = filter.playstyles[i]; clauses.push(`playstyles LIKE $ps${i}`); params[`$ps${i}`] = `%"${ps}"%`; } } if (filter.playstylesPlus && filter.playstylesPlus.length > 0) { for (let i = 0; i < filter.playstylesPlus.length; i++) { const psp = filter.playstylesPlus[i]; clauses.push(`playstyles_plus LIKE $psp${i}`); params[`$psp${i}`] = `%"${psp}"%`; } } if (filter.skillMovesMin !== undefined) { clauses.push("skill_moves >= $sm"); params["$sm"] = filter.skillMovesMin; } if (filter.weakFootMin !== undefined) { clauses.push("weak_foot >= $wf"); params["$wf"] = filter.weakFootMin; } const sortBy = filter.sortBy ?? "overall_rating"; const sortOrder = filter.sortOrder ?? "DESC"; const limit = filter.limit ?? 25; const offset = filter.offset ?? 0; const sql = ` SELECT id, name, overall_rating, position, alternative_positions, club, nation, league, rarity, gender, accelerate_type, pac, sho, pas, dri, def, phy, skill_moves, weak_foot, foot, playstyles, playstyles_plus, url FROM players WHERE ${clauses.join(" AND ")} ORDER BY ${sortBy} ${sortOrder} LIMIT ${limit} OFFSET ${offset} `; const rows = this.db.query(sql).all(params as any) as any[]; return rows.map((r) => { let playstyles: string[] = []; let playstylesPlus: string[] = []; let alternativePositions: string[] = []; try { playstyles = r.playstyles ? JSON.parse(r.playstyles) : []; } catch { playstyles = []; } try { playstylesPlus = r.playstyles_plus ? JSON.parse(r.playstyles_plus) : []; } catch { playstylesPlus = []; } if (r.alternative_positions) { try { const parsed = JSON.parse(r.alternative_positions); if (Array.isArray(parsed)) alternativePositions = parsed; } catch { alternativePositions = r.alternative_positions .split(",") .map((s: string) => s.trim().replace(/^["'\[\]]+|["'\[\]]+$/g, "")) .filter(Boolean); } } return { id: r.id, name: r.name, overallRating: r.overall_rating, position: r.position, alternativePositions, club: r.club ?? "", nation: r.nation ?? "", league: r.league ?? "", rarity: r.rarity ?? "", gender: r.gender ?? "Men", accelerateType: r.accelerate_type ?? "Controlled", pac: r.pac ?? 0, sho: r.sho ?? 0, pas: r.pas ?? 0, dri: r.dri ?? 0, def: r.def ?? 0, phy: r.phy ?? 0, skillMoves: r.skill_moves ?? 3, weakFoot: r.weak_foot ?? 3, foot: r.foot ?? "Right", playstyles, playstylesPlus, url: r.url ?? "", }; }); } public getPlayerById(id: string): PlayerRecord | null { const row = this.db.query("SELECT * FROM players WHERE id = $id LIMIT 1").get({ $id: id }) as any; if (!row) return null; let playstyles: string[] = []; let playstylesPlus: string[] = []; let alternativePositions: string[] = []; try { playstyles = row.playstyles ? JSON.parse(row.playstyles) : []; } catch { playstyles = []; } try { playstylesPlus = row.playstyles_plus ? JSON.parse(row.playstyles_plus) : []; } catch { playstylesPlus = []; } if (row.alternative_positions) { try { const parsed = JSON.parse(row.alternative_positions); if (Array.isArray(parsed)) alternativePositions = parsed; } catch { alternativePositions = row.alternative_positions .split(",") .map((s: string) => s.trim().replace(/^["'\[\]]+|["'\[\]]+$/g, "")) .filter(Boolean); } } return { id: row.id, name: row.name, overallRating: row.overall_rating, position: row.position, alternativePositions, club: row.club ?? "", nation: row.nation ?? "", league: row.league ?? "", rarity: row.rarity ?? "", gender: row.gender ?? "Men", accelerateType: row.accelerate_type ?? "Controlled", pac: row.pac ?? 0, sho: row.sho ?? 0, pas: row.pas ?? 0, dri: row.dri ?? 0, def: row.def ?? 0, phy: row.phy ?? 0, skillMoves: row.skill_moves ?? 3, weakFoot: row.weak_foot ?? 3, foot: row.foot ?? "Right", playstyles, playstylesPlus, url: row.url ?? "", }; } public upsertPlayer(player: Partial): void { try { const rwDb = new Database(this.dbPath); const stmt = rwDb.query(` INSERT INTO players ( id, name, overall_rating, position, alternative_positions, club, nation, league, rarity, gender, accelerate_type, pac, sho, pas, dri, def, phy, skill_moves, weak_foot, foot, playstyles, playstyles_plus, url ) VALUES ( $id, $name, $overall_rating, $position, $alternative_positions, $club, $nation, $league, $rarity, $gender, $accelerate_type, $pac, $sho, $pas, $dri, $def, $phy, $skill_moves, $weak_foot, $foot, $playstyles, $playstyles_plus, $url ) ON CONFLICT(id) DO UPDATE SET name = excluded.name, overall_rating = excluded.overall_rating, position = excluded.position, alternative_positions = excluded.alternative_positions, club = excluded.club, nation = excluded.nation, league = excluded.league, pac = excluded.pac, sho = excluded.sho, pas = excluded.pas, dri = excluded.dri, def = excluded.def, phy = excluded.phy, playstyles = excluded.playstyles, playstyles_plus = excluded.playstyles_plus `); stmt.run({ $id: player.id ?? String(Date.now()), $name: player.name ?? "Unknown", $overall_rating: player.overallRating ?? 80, $position: player.position ?? "CM", $alternative_positions: JSON.stringify(player.alternativePositions ?? []), $club: player.club ?? "", $nation: player.nation ?? "", $league: player.league ?? "", $rarity: player.rarity ?? "Gold Rare", $gender: player.gender ?? "Men", $accelerate_type: player.accelerateType ?? "Controlled", $pac: player.pac ?? 70, $sho: player.sho ?? 70, $pas: player.pas ?? 70, $dri: player.dri ?? 70, $def: player.def ?? 70, $phy: player.phy ?? 70, $skill_moves: player.skillMoves ?? 3, $weak_foot: player.weakFoot ?? 3, $foot: player.foot ?? "Right", $playstyles: JSON.stringify(player.playstyles ?? []), $playstyles_plus: JSON.stringify(player.playstylesPlus ?? []), $url: player.url ?? "", }); rwDb.close(); } catch { // Ignore if DB is locked } } public close(): void { this.db.close(); } }