"""Perfis de jogo bilíngues (doc/clipador/JOGOS.md): inglês para a IA, português para ler, missões, gatilhos de fim, outros nomes, cadastro pelo painel e sementes.""" import json from app.intel import clean_profile from app.judge import JudgeError from tests.test_sources_and_api import FakeJudge, auth, env, seed_session # noqa: F401 - fixture reaproveitada EN = { "name": "Grand Theft Auto VI", "aliases": ["GTA 6", "GTA VI"], "summary": "Open-world crime game in Leonida.", "genre": "Action", "mechanics": ["heists"], "clip_worthy": ["police chase ends in a crash"], "avoid": ["menus"], "jargon": ["wanted level"], "news": ["Released Nov 2026"], "hashtags": ["#GTA6"], "sources": ["https://example.com"], "missions": [{"name": "Hometown", "chapter": "Prologue", "summary": "Lucia and Jason meet.", "completion_triggers": ["MISSION PASSED banner"]}], "end_triggers": ["MISSION PASSED", "WASTED"], } def to_pt(profile: dict) -> dict: """Tradução falsa: marca os textos traduzíveis com [pt] e mantém o resto, como o TRANSLATE_SYSTEM pede.""" out = json.loads(json.dumps(profile)) out["summary"] = "[pt] " + out["summary"] out["clip_worthy"] = ["[pt] " + x for x in out["clip_worthy"]] for m in out["missions"]: m["summary"] = "[pt] " + m["summary"] return out class BilingualJudge(FakeJudge): def __init__(self, fail_translate=False): super().__init__() self.fail_translate = fail_translate self.translations: list[str] = [] def research_game(self, name, live_title="", notes=None): return {**EN, "name": name} def translate_game(self, profile, target): self.translations.append(target) if self.fail_translate: raise JudgeError("cota acabou") if target == "pt-BR": return to_pt(profile) back = json.loads(json.dumps(profile)) back["summary"] = "[en] " + back["summary"] return back def refine_game(self, name, profile, instruction, search=True, section="", history=None): return {**profile, "end_triggers": [*profile["end_triggers"], "Reward screen"], "reply": "Acrescentei a tela de recompensa."} def add(engine, name="Grand Theft Auto VI"): engine.db.run("INSERT INTO games (id, name, status) VALUES (?, ?, 'pending')", name.lower().replace(" ", "-"), name) return name.lower().replace(" ", "-") def test_research_stores_english_for_ai_and_portuguese_for_reading(env): # noqa: F811 client, engine = env engine.judge = BilingualJudge() gid = add(engine) engine.intel.research(gid) game = client.get("/v1/games", headers=auth()).json()["games"][0] assert game["status"] == "ready" and game["aiLanguage"] == "en-US" and game["translatedAt"] assert game["profileAi"]["summary"] == EN["summary"] assert game["profile"]["summary"].startswith("[pt] ") # Nome oficial da missão e hashtags não mudam na tradução. assert game["profile"]["missions"][0]["name"] == "Hometown" and game["profile"]["hashtags"] == ["#GTA6"] assert game["aliases"] == ["gta-6", "gta-vi"] # A IA lê o inglês. assert engine.intel.profile("Grand Theft Auto VI")["summary"] == EN["summary"] def test_failed_translation_keeps_english_in_both_and_explains(env): # noqa: F811 client, engine = env engine.judge = BilingualJudge(fail_translate=True) gid = add(engine) engine.intel.research(gid) game = client.get("/v1/games", headers=auth()).json()["games"][0] assert game["status"] == "ready" and "tradução falhou" in game["error"] assert game["profile"]["summary"] == EN["summary"] and game["translatedAt"] is None def test_manual_save_in_portuguese_translates_to_english(env): # noqa: F811 client, engine = env engine.judge = BilingualJudge() gid = add(engine) engine.intel.research(gid) pt = to_pt(EN) pt["summary"] = "Jogo de crime em Leonida, editado por mim." r = client.put(f"/v1/games/{gid}", json=pt, headers=auth()) assert r.status_code == 200 game = r.json()["games"][0] assert game["profile"]["summary"] == "Jogo de crime em Leonida, editado por mim." assert game["profileAi"]["summary"] == "[en] Jogo de crime em Leonida, editado por mim." and game["editedAt"] assert engine.judge.translations[-1] == "en-US" # Editar a versão da IA direto (lang=en) traduz para português. r = client.put(f"/v1/games/{gid}?lang=en", json=EN, headers=auth()) assert r.json()["games"][0]["profileAi"]["summary"] == EN["summary"] assert engine.judge.translations[-1] == "pt-BR" def test_refine_applies_on_english_and_replies_in_portuguese(env): # noqa: F811 client, engine = env engine.judge = BilingualJudge() gid = add(engine) engine.intel.research(gid) r = client.post(f"/v1/games/{gid}/refine", json={"instruction": "acrescente a tela de recompensa", "section": "end_triggers"}, headers=auth()) assert r.status_code == 200 and r.json()["reply"] == "Acrescentei a tela de recompensa." game = r.json()["games"][0] assert "Reward screen" in game["profileAi"]["end_triggers"] and "Reward screen" in game["profile"]["end_triggers"] def test_context_uses_english_profile_with_missions_and_end_triggers(env): # noqa: F811 client, engine = env engine.judge = BilingualJudge() engine.intel.research(add(engine)) sid = seed_session(engine) # Categoria por outro nome ("GTA 6") cai no mesmo perfil. engine.db.run("UPDATE sessions SET game = 'GTA 6' WHERE id = ?", sid) context = engine.intel.context(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)) assert EN["summary"] in context and "MISSION PASSED; WASTED" in context assert "Hometown (fim: MISSION PASSED banner)" in context and "termine o corte logo depois do gatilho" in context def test_mission_list_in_prompt_is_capped(): from app.judge import mission_lines profile = clean_profile({"missions": [{"name": f"Mission number {i}", "completion_triggers": ["MISSION PASSED"]} for i in range(110)]}) lines = mission_lines(profile) assert len(profile["missions"]) == 110 missions = next(line for line in lines if line.startswith("Missões")) assert "…e mais" in missions and len(missions) < 1700 def test_add_game_conflicts_by_alias_and_delete(env): # noqa: F811 client, engine = env engine.judge = BilingualJudge() engine.intel.research(add(engine)) r = client.post("/v1/games", json={"name": "GTA 6"}, headers=auth()) assert r.status_code == 409 and "já está na lista" in r.json()["error"] r = client.post("/v1/games", json={"name": "Hollow Knight: Silksong", "notes": "foco em chefes"}, headers=auth()) assert r.status_code == 201 and r.json()["id"] == "hollow-knight-silksong" new = next(g for g in r.json()["games"] if g["id"] == "hollow-knight-silksong") assert new["notes"][0]["text"] == "foco em chefes" r = client.delete("/v1/games/hollow-knight-silksong", headers=auth()) assert r.status_code == 200 and all(g["id"] != "hollow-knight-silksong" for g in r.json()["games"]) assert client.delete("/v1/games/nao-existe", headers=auth()).status_code == 404 def test_translate_route_makes_ai_version_for_old_games(env): # noqa: F811 client, engine = env engine.judge = BilingualJudge() engine.db.run("INSERT INTO games (id, name, status, profile_json) VALUES ('rob-run', 'ROB RUN', 'ready', ?)", json.dumps(clean_profile({"name": "ROB RUN", "summary": "Jogo de assalto."}))) assert client.get("/v1/games", headers=auth()).json()["games"][0]["profileAi"] is None r = client.post("/v1/games/rob-run/translate", headers=auth()) assert r.status_code == 200 and r.json()["games"][0]["profileAi"]["summary"] == "[en] Jogo de assalto." def test_seeds_import_once_and_never_overwrite(env, tmp_path): # noqa: F811 _, engine = env folder = tmp_path / "seeds" folder.mkdir() (folder / "game.json").write_text(json.dumps({ "name": "Seed Game", "aliases": ["SG"], "researchedAt": "2026-11-18T00:00:00+00:00", "sources": ["https://a"], "profileAi": {"summary": "English summary", "missions": [{"name": "M1"}]}, "profile": {"summary": "Resumo em português", "missions": [{"name": "M1"}]}, }), encoding="utf-8") assert engine.intel.import_seeds(folder) == ["seed-game"] row = engine.db.get("SELECT * FROM games WHERE id = 'seed-game'") assert row["status"] == "ready" and row["model"] == "seed" assert json.loads(row["profile_ai_json"])["aliases"] == ["SG"] and json.loads(row["profile_json"])["sources"] == ["https://a"] assert engine.intel.profile("SG")["summary"] == "English summary" engine.db.run("UPDATE games SET profile_json = '{\"summary\": \"editado\"}' WHERE id = 'seed-game'") assert engine.intel.import_seeds(folder) == [] assert json.loads(engine.db.get("SELECT profile_json FROM games WHERE id = 'seed-game'")["profile_json"])["summary"] == "editado" def test_category_by_alias_does_not_create_duplicate_game(env): # noqa: F811 _, engine = env engine.judge = BilingualJudge() engine.intel.research(add(engine)) sid = seed_session(engine) engine.intel.set_game(sid, "GTA VI", "platform") assert [r["id"] for r in engine.db.all("SELECT id FROM games")] == ["grand-theft-auto-vi"]