import copy
import json
from pathlib import Path

from app.canon_log import validate_origin
from app.content import load_world, load_origin, unresolved_refs

REPO_ROOT = Path(__file__).resolve().parents[2]
CONTENT_ROOT = REPO_ROOT / "content"
DESERTER = CONTENT_ROOT / "origins" / "deserter.json"


def test_deserter_origin_matches_schema():
    assert validate_origin(load_origin(DESERTER)) == []


def test_deserter_ids_all_resolve():
    world = load_world(CONTENT_ROOT)
    assert unresolved_refs(load_origin(DESERTER), world) == []


def test_broken_location_ref_is_detected():
    world = load_world(CONTENT_ROOT)
    origin = copy.deepcopy(load_origin(DESERTER))
    origin["start_location_id"] = "nowhere"
    assert "location:nowhere" in unresolved_refs(origin, world)


def test_broken_item_ref_is_detected():
    world = load_world(CONTENT_ROOT)
    origin = copy.deepcopy(load_origin(DESERTER))
    origin["inventory_grants"].append({"item_id": "ghost_blade", "qty": 1})
    assert "item:ghost_blade" in unresolved_refs(origin, world)


def test_null_quest_ref_resolves():
    world = load_world(CONTENT_ROOT)
    origin = copy.deepcopy(load_origin(DESERTER))
    origin["start_quest_id"] = None
    assert unresolved_refs(origin, world) == []


def test_broken_disposition_npc_ref_is_detected():
    world = load_world(CONTENT_ROOT)
    origin = copy.deepcopy(load_origin(DESERTER))
    origin["disposition_overrides"]["ghost_npc"] = 10
    assert "npc:ghost_npc" in unresolved_refs(origin, world)
