# -*- coding: utf-8 -*- # models/database.py import sqlite3 from pathlib import Path import resources.code_res.sql_queries as sql from resources.code_res.game_constants import ( BJ_DEFAULT_BET, BJ_STARTING_GOLD, DEVILS_DEAL_GOLD_REWARD, GOLD_MAX_ACCOUNTS, INTERNAL_DB_REL_PATH, USER_DB_FILENAME, XP_TO_GOLD_AMOUNT ) ROOT_DIR = Path(__file__).resolve().parent.parent INTERNAL_DB_PATH = ROOT_DIR / INTERNAL_DB_REL_PATH USER_DB_PATH = ROOT_DIR / USER_DB_FILENAME class Database: _connection: sqlite3.Connection | None = None @classmethod def conn(cls) -> sqlite3.Connection: if cls._connection is None: if not INTERNAL_DB_PATH.is_file(): raise FileNotFoundError( f"Interne Stammdaten-DB fehlt: {INTERNAL_DB_PATH}. " "Bitte zuerst das Seed-SQL mit deinem Query-Executor ausführen!" ) c = sqlite3.connect(USER_DB_PATH) c.row_factory = sqlite3.Row c.execute(sql.PRAGMA_FOREIGN_KEYS) c.execute(sql.ATTACH_INTERNAL_DB, (str(INTERNAL_DB_PATH),)) cls._connection = c return cls._connection @classmethod def close(cls): if cls._connection is not None: cls._connection.close() cls._connection = None @classmethod def execute(cls, query: str, params: tuple = ()) -> sqlite3.Cursor: cur = cls.conn().execute(query, params) cls.conn().commit() return cur @classmethod def execute_many(cls, query: str, seq_of_params) -> sqlite3.Cursor: cur = cls.conn().executemany(query, seq_of_params) cls.conn().commit() return cur @classmethod def fetch_one(cls, query: str, params: tuple = ()) -> dict | None: row = cls.conn().execute(query, params).fetchone() return dict(row) if row else None @classmethod def fetch_all(cls, query: str, params: tuple = ()) -> list[dict]: return [dict(r) for r in cls.conn().execute(query, params).fetchall()] @classmethod def fetch_val(cls, query: str, params: tuple = (), default=None): row = cls.conn().execute(query, params).fetchone() return row[0] if row is not None else default @classmethod def init_db(cls): cls.conn().executescript(sql.USER_SCHEMA_DDL) bj_cols = [r["name"] for r in cls.fetch_all(sql.PRAGMA_TABLE_INFO_BJ_ACCOUNTS)] if "devils_deal_active" not in bj_cols: cls.conn().execute(sql.MIGRATE_ADD_DEVILS_ACTIVE) cls.conn().commit() @classmethod def load_all_translations(cls) -> dict[str, dict[str, str]]: out: dict[str, dict[str, str]] = {"DE": {}, "EN": {}} for r in cls.fetch_all(sql.SELECT_ALL_I18N): out.setdefault(r["lang"], {})[r["key"]] = r["val"] return out @classmethod def load_prestige_ranks(cls) -> list[dict]: return cls.fetch_all(sql.SELECT_PRESTIGE_RANKS) @classmethod def load_setting(cls, key: str, default: str = "") -> str: return cls.fetch_val(sql.SELECT_SETTING, (key,), default=default) @classmethod def save_setting(cls, key: str, value: str): cls.execute(sql.UPSERT_SETTING, (key, str(value))) # --- Profile (reiner Account ohne übergreifendes Level!) --- @classmethod def get_profiles(cls) -> list[str]: return [r["name"] for r in cls.fetch_all(sql.SELECT_ALL_PROFILES)] @classmethod def get_or_create_profile(cls, name: str) -> dict: cls.execute(sql.INSERT_PROFILE_IGNORE, (name,)) return cls.fetch_one(sql.SELECT_PROFILE_BY_NAME, (name,)) @classmethod def get_profile_by_id(cls, profile_id: int) -> dict | None: return cls.fetch_one(sql.SELECT_PROFILE_BY_ID, (profile_id,)) # --- Spielgebundene Progression (eigenes Level je Spiel!) --- @classmethod def get_game_progress(cls, profile_id: int, game_folder: str) -> dict: from models.progression import Progression cls.execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder)) row = cls.fetch_one(sql.SELECT_GAME_PROGRESS, (profile_id, game_folder)) info = Progression.get_level_info( row["points"], profile_id=profile_id, game_folder=game_folder, ever_deity=bool(row["ever_reached_deity"]), ) if info["ever_reached_deity"] and not row["ever_reached_deity"]: cls.execute(sql.MARK_GAME_EVER_DEITY, (profile_id, game_folder)) return info @classmethod def get_recorded_game_level_avg_xp(cls, profile_id: int, game_folder: str, level_num: int) -> int: row = cls.fetch_one(sql.SELECT_GAME_LEVEL_AVG_XP, (profile_id, game_folder, int(level_num))) if not row or row["games_count"] <= 0: return 0 return int(row["total_xp_earned"] // row["games_count"]) @classmethod def _record_game_xp_with_history(cls, profile_id: int, game_folder: str, current_level: int, xp_gained: int): from models.progression import Progression if xp_gained <= 0: return cls.conn().execute(sql.INSERT_GAME_PROGRESS_IGNORE, (profile_id, game_folder)) cls.conn().execute(sql.ADD_GAME_POINTS, (int(xp_gained), profile_id, game_folder)) if current_level >= Progression.get_creator_spirit_v_level(): cls.conn().execute( sql.UPSERT_GAME_LEVEL_XP_HISTORY, (profile_id, game_folder, int(current_level), int(xp_gained)) ) @classmethod def add_game_points(cls, profile_id: int, game_folder: str, points: int): if points <= 0: return cur_prog = cls.get_game_progress(profile_id, game_folder) with cls.conn(): cls._record_game_xp_with_history(profile_id, game_folder, cur_prog["level"], int(points)) cls.get_game_progress(profile_id, game_folder) @classmethod def adjust_game_points(cls, profile_id: int, game_folder: str, delta_points: int, min_floor_xp: int = 0) -> dict: """Für künftige Spiel-spezifische Rückstufungen (z.B. Solitaire-Strafen).""" cur = cls.get_game_progress(profile_id, game_folder) new_pts = max(min_floor_xp, cur["total_points"] + int(delta_points)) cls.execute(sql.SET_GAME_POINTS, (new_pts, profile_id, game_folder)) return cls.get_game_progress(profile_id, game_folder) # --- Spielgebundener THE DEVIL'S DEAL (Opfer muss Rang 'Stütze I' IM SELBEN SPIEL haben!) --- @classmethod def get_sacrificeable_profiles(cls, active_profile_id: int, game_folder: str) -> list[dict]: from models.progression import Progression min_lvl = Progression.get_devils_deal_min_level() eligible = [] for row in cls.fetch_all(sql.SELECT_CANDIDATES_FOR_GAME_SACRIFICE, (game_folder, active_profile_id)): info = Progression.get_level_info(row["points"]) if info["level"] >= min_lvl: eligible.append({ "id": row["id"], "name": row["name"], "level": info["level"], "title": info["title"], }) return eligible @classmethod def execute_devils_deal( cls, active_profile_id: int, game_folder: str, sacrifice_profile_id: int, bj_account_id: int ) -> tuple[bool, str]: from resources.code_res.i18n import t candidates = {c["id"]: c for c in cls.get_sacrificeable_profiles(active_profile_id, game_folder)} victim = candidates.get(sacrifice_profile_id) if not victim: return False, "" with cls.conn(): cls.conn().execute(sql.DELETE_PROFILE_BY_ID, (sacrifice_profile_id,)) cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (DEVILS_DEAL_GOLD_REWARD, bj_account_id)) cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1, bj_account_id)) acc = cls.get_blackjack_account(bj_account_id) return True, t("bj_devils_deal_success", victim["name"], DEVILS_DEAL_GOLD_REWARD, acc["account_name"]) @classmethod def get_active_devils_bj_account(cls, profile_id: int) -> dict | None: return cls.fetch_one(sql.SELECT_ACTIVE_DEVILS_BJ_ACCOUNT, (profile_id,)) @classmethod def set_bj_devils_deal_active(cls, bj_account_id: int, active: bool): cls.execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (1 if active else 0, bj_account_id)) # --- Savegames --- @classmethod def save_game_state(cls, profile_id: int, game_folder: str, variant_key: str, state_json: str): cls.execute(sql.UPSERT_SAVEGAME, (profile_id, game_folder, variant_key, state_json)) @classmethod def load_game_state(cls, profile_id: int, game_folder: str) -> dict | None: return cls.fetch_one(sql.SELECT_SAVEGAME, (profile_id, game_folder)) @classmethod def delete_game_state(cls, profile_id: int, game_folder: str): cls.execute(sql.DELETE_SAVEGAME, (profile_id, game_folder)) # --- Blackjack Gold-Konten & Blackjack-spezifischer XP->Gold-Tausch --- @classmethod def get_blackjack_accounts(cls, profile_id: int) -> list[dict]: return cls.fetch_all(sql.SELECT_BJ_ACCOUNTS_BY_PROFILE, (profile_id,)) @classmethod def get_blackjack_account(cls, bj_account_id: int) -> dict | None: return cls.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_ID, (bj_account_id,)) @classmethod def create_blackjack_account(cls, profile_id: int, account_name: str) -> dict: from resources.code_res.i18n import t clean_name = account_name.strip() if not clean_name: raise ValueError(t("bj_err_empty_name")) if len(cls.get_blackjack_accounts(profile_id)) >= GOLD_MAX_ACCOUNTS: raise RuntimeError(t("bj_max_acc_reached", GOLD_MAX_ACCOUNTS)) cls.execute(sql.INSERT_BJ_ACCOUNT, (profile_id, clean_name, BJ_STARTING_GOLD, BJ_DEFAULT_BET)) return cls.fetch_one(sql.SELECT_BJ_ACCOUNT_BY_NAME, (profile_id, clean_name)) @classmethod def update_blackjack_gold(cls, bj_account_id: int, gold_delta: int, last_bet: int | None = None) -> dict: if last_bet is not None: cls.execute(sql.UPDATE_BJ_GOLD_AND_BET, (int(gold_delta), int(last_bet), bj_account_id)) else: cls.execute(sql.UPDATE_BJ_GOLD_ONLY, (int(gold_delta), bj_account_id)) return cls.get_blackjack_account(bj_account_id) @classmethod def save_blackjack_last_bet(cls, bj_account_id: int, bet: int): cls.execute(sql.UPDATE_BJ_LAST_BET, (int(bet), bj_account_id)) @classmethod def delete_blackjack_account(cls, bj_account_id: int): cls.execute(sql.DELETE_BJ_ACCOUNT, (bj_account_id,)) @classmethod def exchange_xp_for_bj_gold(cls, profile_id: int, bj_account_id: int) -> tuple[bool, str]: """Zieht XP AUSSCHLIESSLICH vom Blackjack-Spielfortschritt ('blackjack') ab!""" from models.progression import Progression from resources.code_res.i18n import t bj_prog = cls.get_game_progress(profile_id, "blackjack") if bj_prog.get("at_divine_floor"): return False, t("bj_err_floor_reached") cost = bj_prog["xp_exchange_cost"] is_divine = bj_prog["is_divine_punishment"] if not is_divine and bj_prog["total_points"] < cost: return False, t("bj_err_not_enough_xp", bj_prog["total_points"], cost) if is_divine: floor_xp = Progression.get_creator_spirit_v_floor_xp() new_points = max(floor_xp, bj_prog["total_points"] - cost) actual_deducted = bj_prog["total_points"] - new_points if actual_deducted <= 0: return False, t("bj_err_floor_reached") else: new_points = max(0, bj_prog["total_points"] - cost) actual_deducted = cost with cls.conn(): cls.conn().execute(sql.SET_GAME_POINTS, (new_points, profile_id, "blackjack")) cls.conn().execute(sql.UPDATE_BJ_GOLD_ONLY, (XP_TO_GOLD_AMOUNT, bj_account_id)) cls.conn().execute(sql.SET_BJ_DEVILS_DEAL_ACTIVE, (0, bj_account_id)) acc = cls.get_blackjack_account(bj_account_id) updated_prog = cls.get_game_progress(profile_id, "blackjack") if is_divine: return True, t( "bj_exchange_divine_success", XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted, updated_prog["title"] ) return True, t("bj_exchange_success", XP_TO_GOLD_AMOUNT, acc["account_name"], actual_deducted) # --- Bot Configs & Statistiken --- @classmethod def load_bot_configs(cls, profile_id: int, game_folder: str) -> dict[int, tuple[str, int]]: rows = cls.fetch_all(sql.SELECT_BOT_CONFIGS, (profile_id, game_folder)) return {r["slot_idx"]: (r["bot_name"], r["ai_level"]) for r in rows} @classmethod def save_bot_configs(cls, profile_id: int, game_folder: str, configs: dict[int, tuple[str, int]]): data = [(profile_id, game_folder, int(idx), name, int(lvl)) for idx, (name, lvl) in configs.items()] cls.execute_many(sql.UPSERT_BOT_CONFIG, data) @classmethod def _upsert_stat(cls, scope: str, owner_id: int, variant_id: int, won: bool, duration_sec: float): q = sql.STATS_SQL[scope] cur = cls.fetch_one(q["select_one"], (owner_id, variant_id)) dur = max(0.0, duration_sec) if not cur: cls.conn().execute(q["insert"], ( owner_id, variant_id, 1 if won else 0, 0 if won else 1, 1 if won else 0, 1 if won else 0, dur if won else None, dur, )) else: c_streak = (cur["current_streak"] + 1) if won else 0 best_t = cur["best_time_sec"] if won: best_t = dur if best_t is None else min(best_t, dur) cls.conn().execute(q["update"], ( cur["games_played"] + 1, cur["games_won"] + (1 if won else 0), cur["games_lost"] + (0 if won else 1), c_streak, max(cur["longest_streak"], c_streak), best_t, cur["total_time_sec"] + dur, owner_id, variant_id, )) @classmethod def record_game_result( cls, profile_id: int, variant_key: str, won: bool, duration_sec: float, points_gained: int = 0, bj_account_id: int | None = None ) -> tuple[int, int]: """Ermittelt aus variant_key automatisch den game_folder und bucht XP nur auf dieses Spiel!""" var_info = cls.fetch_one(sql.SELECT_VARIANT_INFO_BY_KEY, (variant_key,)) if not var_info: raise ValueError(f"Unbekannte Spielvariante in internal_base.db: {variant_key}") variant_id = var_info["id"] game_folder = var_info["folder_path"] prog_before = cls.get_game_progress(profile_id, game_folder) old_lvl = prog_before["level"] with cls.conn(): if points_gained > 0: cls._record_game_xp_with_history(profile_id, game_folder, old_lvl, int(points_gained)) cls._upsert_stat("profile", profile_id, variant_id, won, duration_sec) if bj_account_id is not None: cls._upsert_stat("bj_account", bj_account_id, variant_id, won, duration_sec) new_lvl = cls.get_game_progress(profile_id, game_folder)["level"] return old_lvl, new_lvl @classmethod def get_variants_for_filter(cls, folder_path: str | None = None) -> list[dict]: from resources.code_res.i18n import t rows = ( cls.fetch_all(sql.SELECT_VARIANTS_BY_FOLDER, (folder_path,)) if folder_path else cls.fetch_all(sql.SELECT_ALL_VARIANTS) ) for d in rows: d["translated_name"] = t(f"variant_{d['variant_key']}") return rows @classmethod def _query_stats(cls, scope: str, owner_id: int, variant_id: int | None = None, folder_path: str | None = None) -> dict: q = sql.STATS_SQL[scope] if variant_id is not None: row = cls.fetch_one(q["select_one"], (owner_id, variant_id)) if not row or row["games_played"] == 0: return cls._empty_stats() played, won, lost = row["games_played"], row["games_won"], row["games_lost"] c_streak, l_streak, best_t, total_t = row["current_streak"], row["longest_streak"], row["best_time_sec"], row["total_time_sec"] else: row = ( cls.fetch_one(q["aggregate_folder"], (owner_id, folder_path)) if folder_path is not None else cls.fetch_one(q["aggregate_all"], (owner_id,)) ) if not row or row["played"] == 0: return cls._empty_stats() played, won, lost = row["played"], row["won"], row["lost"] c_streak, l_streak, best_t, total_t = row["c_streak"], row["l_streak"], row["best_time"], row["total_time"] return { "played": played, "won": won, "lost": lost, "win_pct": f"{(won / played * 100.0):.1f} %", "current_streak": c_streak, "longest_streak": l_streak, "best_time": cls.format_seconds(best_t), "avg_time": cls.format_seconds(total_t / played), } @classmethod def get_stats_overview(cls, profile_id: int, variant_id: int | None = None, folder_path: str | None = None) -> dict: return cls._query_stats("profile", profile_id, variant_id=variant_id, folder_path=folder_path) @classmethod def get_bj_account_stats_overview(cls, bj_account_id: int, variant_id: int | None = None) -> dict: return cls._query_stats("bj_account", bj_account_id, variant_id=variant_id, folder_path="blackjack") @staticmethod def format_seconds(sec: float | None) -> str: if sec is None: return "--:--" mins, secs = divmod(int(round(sec)), 60) if mins >= 60: hrs, mins = divmod(mins, 60) return f"{hrs:02d}:{mins:02d}:{secs:02d}" return f"{mins:02d}:{secs:02d}" @staticmethod def _empty_stats() -> dict: return { "played": 0, "won": 0, "lost": 0, "win_pct": "0.0 %", "current_streak": 0, "longest_streak": 0, "best_time": "--:--", "avg_time": "--:--", }