import sys
from server.world.map_biome_catalog import get_biome_definition, get_biome_by_code
from server.world.map_style_catalog import get_map_style, get_map_style_by_code
from server.world.map_binary_serializer import serialize_map_grid, deserialize_map_grid
from server.world.wilderness_map_generator import WildernessMapGenerator, ZONE_CANONICAL_BIOMES, ZONE_DEFAULT_SIZES

sys.stdout.reconfigure(encoding='utf-8')

print("=== VERIFYING LEGACY BIOMES 1-5 ===")
legacy_biomes = [
    (1, "BLEACHED_BONE_CANYON", "STY_11_HEM_NUI_XUONG_TRANG"),
    (2, "SAVAGE_MANGROVE_SWAMP", "STY_06_BAI_THA_MA_NGAP_MAN"),
    (3, "CRIMSON_BLOOD_FOREST", "STY_02_HUYET_SAT_LAM"),
    (4, "OUTCAST_MINE_SHAFTS", "STY_16_MO_QUANG_LUU_DAY"),
    (5, "CORRUPTED_FIEND_RUINS", "STY_21_PHE_TICH_MA_THAN"),
]

for code, legacy_name, style_id in legacy_biomes:
    # 1. By code
    b_by_code = get_biome_by_code(code)
    assert b_by_code is not None, f"Biome code {code} not found in map_biome_catalog"
    s_by_code = get_map_style_by_code(code)
    assert s_by_code is not None, f"Style code {code} not found in map_style_catalog"
    assert s_by_code.style_id == style_id, f"Expected {style_id}, got {s_by_code.style_id}"
    
    # 2. By legacy name
    b_by_name = get_biome_definition(legacy_name)
    assert b_by_name.biome_code == code
    s_by_name = get_map_style(legacy_name)
    assert s_by_name is not None and s_by_name.biome_code == code
    
    # 3. By style_id
    b_by_style = get_biome_definition(style_id)
    assert b_by_style.biome_code == code
    s_by_style = get_map_style(style_id)
    assert s_by_style.biome_code == code
    
    print(f"[PASS] Legacy Biome {code}: {legacy_name} <-> {style_id} resolved correctly across all APIs.")

print("\n=== VERIFYING CANONICAL ZONES GENERATION ===")
for zone_id, canonical_biome in ZONE_CANONICAL_BIOMES.items():
    gen = WildernessMapGenerator.for_zone(zone_id, seed=12345)
    grid_data = gen.generate(seed=12345)
    
    assert grid_data.width >= 60 and grid_data.height >= 45, f"Zone {zone_id} has invalid dimensions {(grid_data.width, grid_data.height)}"
    assert grid_data.spawn_point is not None, f"Zone {zone_id} missing spawn point"
    assert grid_data.boss_gate is not None, f"Zone {zone_id} missing boss gate"
    
    # Test binary serialization & roundtrip
    bin_bytes = serialize_map_grid(grid_data)
    assert len(bin_bytes) > 16, f"Serialized bytes too small for {zone_id}"
    assert bin_bytes[:2] == b"FE", f"Magic header mismatch for {zone_id}"
    
    deserialized = deserialize_map_grid(bin_bytes)
    assert deserialized.width == grid_data.width
    assert deserialized.height == grid_data.height
    assert deserialized.spawn_point == grid_data.spawn_point
    
    print(f"[PASS] Zone {zone_id}: biome={canonical_biome}, dims=({grid_data.width}x{grid_data.height}), binary_len={len(bin_bytes)} bytes")

print("\n[ALL PASS] Backward compatibility with legacy biomes 1-5 and canonical zones verified 100%!")
