from pathlib import Path
import json, tempfile
from app import db
from app.services.context_builder import relevant_world_bible

orig = db.DB_PATH
with tempfile.TemporaryDirectory() as td:
    db.DB_PATH = Path(td) / 'legacy.db'
    db.init_db()
    cid = db.execute("INSERT INTO conversations(title,persona_name,scenario_name) VALUES (?,?,?)", ("Legacy RP","Mara","Legacy"))
    legacy = {
        "name": "Legacy World",
        "description": "Legacy description survives.",
        "timeline": ["Legacy treaty signed."],
        "organizations": ["Legacy Guild"],
        "vehicles": ["Black motorcycle"],
        "pets": ["A cat named Ash"],
        "characters": [{"name":"Rowan"}],
        "locations": [{"name":"Old Keep"}],
    }
    db.execute("INSERT INTO state_docs(conversation_id,doc_type,payload) VALUES (?,?,?)", (cid,"world_bible",json.dumps(legacy)))
    # Re-running startup migrations must enrich, not overwrite, the legacy save.
    db.init_db()
    world = db.get_state(cid)["world_bible"]
    assert world["schema_version"] >= 4
    assert world["overview"]["name"] == "Legacy World"
    assert world["overview"]["description"] == "Legacy description survives."
    assert any("Legacy treaty" in str(x) for x in world["story_timeline"])
    assert any("Legacy Guild" in str(x) for x in world["groups_factions"])
    assert any("motorcycle" in str(x).lower() for x in world["important_objects"])
    assert any("cat named Ash" in str(x) for x in world["custom_entries"])
    ctx = relevant_world_bible(world, "Ash Legacy Guild treaty motorcycle", 42)
    assert any("Legacy treaty" in str(x) for x in ctx.get("story_timeline", []))
    assert any("Legacy Guild" in str(x) for x in ctx.get("groups_factions", []))
    assert any("motorcycle" in str(x).lower() for x in ctx.get("important_objects", []))
    assert any("Ash" in str(x) for x in ctx.get("custom_entries", []))
    print("PASS legacy World Bible migration regression")
db.DB_PATH = orig
