"""Small configurable identity directory used by interactive character entry.""" from __future__ import annotations import json import os import sqlite3 from dataclasses import dataclass from pathlib import Path from typing import Any @dataclass(frozen=True) class Identity: name: str character_id: int class IdentityDirectory: """Resolve and persist character name/ID pairs in PostgreSQL or local SQLite.""" def __init__(self, identities: list[Identity] | None = None, db_path: str | Path | None = None, database_url: str | None = None) -> None: self.db_path = Path(db_path) if db_path else None self.database_url = database_url or "" self._by_id: dict[int, Identity] = {} self._by_name: dict[str, Identity] = {} self._profiles: dict[int, Identity] = {} if self.database_url.startswith(("postgres://", "postgresql://")): import psycopg self._psycopg = psycopg with psycopg.connect(self.database_url) as connection: connection.execute( "CREATE TABLE IF NOT EXISTS identities (character_id BIGINT PRIMARY KEY, name TEXT NOT NULL)" ) connection.execute( "CREATE TABLE IF NOT EXISTS profiles (actor_id BIGINT PRIMARY KEY, name TEXT NOT NULL, character_id BIGINT NOT NULL)" ) identities = [Identity(name, character_id) for character_id, name in connection.execute( "SELECT character_id, name FROM identities" )] elif self.db_path: self.db_path.parent.mkdir(parents=True, exist_ok=True) with sqlite3.connect(self.db_path) as connection: connection.execute( "CREATE TABLE IF NOT EXISTS identities (character_id INTEGER PRIMARY KEY, name TEXT NOT NULL)" ) connection.execute( "CREATE TABLE IF NOT EXISTS profiles (actor_id INTEGER PRIMARY KEY, name TEXT NOT NULL, character_id INTEGER NOT NULL)" ) identities = [Identity(name, character_id) for character_id, name in connection.execute( "SELECT character_id, name FROM identities" )] for item in identities or []: self._index(item) @classmethod def from_environment(cls, *, persistent: bool = True) -> "IdentityDirectory": raw = os.getenv("BELKI_IDENTITIES_JSON", "") identities: list[Identity] = [] try: if raw: data: Any = json.loads(raw) rows = data.get("characters", data) if isinstance(data, dict) else data identities = [Identity(name=str(row["name"]), character_id=int(row["id"])) for row in rows] except (TypeError, ValueError, KeyError, json.JSONDecodeError) as exc: raise ValueError("BELKI_IDENTITIES_JSON должен содержать список {name,id}") from exc database_url = os.getenv("BELKI_DATABASE_URL", "") if persistent else "" db_path = os.getenv("BELKI_IDENTITIES_DB", "data/belki.sqlite3") if persistent and not database_url else None directory = cls(identities, db_path=db_path, database_url=database_url) for item in identities: directory.remember(name=item.name, character_id=item.character_id) return directory def _index(self, identity: Identity) -> None: self._by_id[identity.character_id] = identity self._by_name[identity.name.casefold()] = identity def resolve(self, *, name: str | None = None, character_id: int | None = None) -> Identity | None: if character_id is not None and character_id in self._by_id: return self._by_id[character_id] if name and name.casefold() in self._by_name: return self._by_name[name.casefold()] return None def remember(self, *, name: str, character_id: int) -> Identity: identity = Identity(name=name.strip(), character_id=character_id) if self.database_url.startswith(("postgres://", "postgresql://")): with self._psycopg.connect(self.database_url) as connection: connection.execute( "INSERT INTO identities(character_id, name) VALUES (%s, %s) " "ON CONFLICT(character_id) DO UPDATE SET name=excluded.name", (identity.character_id, identity.name), ) elif self.db_path: with sqlite3.connect(self.db_path) as connection: connection.execute( "INSERT INTO identities(character_id, name) VALUES (?, ?) " "ON CONFLICT(character_id) DO UPDATE SET name=excluded.name", (identity.character_id, identity.name), ) self._index(identity) return identity def remember_profile(self, *, actor_id: int, name: str, character_id: int) -> Identity: identity = self.remember(name=name, character_id=character_id) self._profiles[actor_id] = identity if self.database_url.startswith(("postgres://", "postgresql://")): with self._psycopg.connect(self.database_url) as connection: connection.execute( "INSERT INTO profiles(actor_id, name, character_id) VALUES (%s, %s, %s) " "ON CONFLICT(actor_id) DO UPDATE SET name=excluded.name, character_id=excluded.character_id", (actor_id, identity.name, identity.character_id), ) elif self.db_path: with sqlite3.connect(self.db_path) as connection: connection.execute( "INSERT INTO profiles(actor_id, name, character_id) VALUES (?, ?, ?) " "ON CONFLICT(actor_id) DO UPDATE SET name=excluded.name, character_id=excluded.character_id", (actor_id, identity.name, identity.character_id), ) return identity def profile(self, *, actor_id: int) -> Identity | None: if actor_id in self._profiles: return self._profiles[actor_id] if self.database_url.startswith(("postgres://", "postgresql://")): with self._psycopg.connect(self.database_url) as connection: row = connection.execute( "SELECT name, character_id FROM profiles WHERE actor_id = %s", (actor_id,) ).fetchone() elif self.db_path: with sqlite3.connect(self.db_path) as connection: row = connection.execute( "SELECT name, character_id FROM profiles WHERE actor_id = ?", (actor_id,) ).fetchone() else: return None identity = Identity(row[0], row[1]) if row else None if identity: self._profiles[actor_id] = identity return identity def suggest(self, *, name: str | None = None, character_id: int | None = None) -> str: if name and character_id is None: return f"Для «{name}» не найдена связка. Введите ID или добавьте её в справочник." if character_id is not None and not name: return f"Для ID {character_id} не найдена связка. Введите имя или добавьте её в справочник." return "Связка имени и ID не найдена. Добавьте недостающее значение или настройте справочник."