import sqlite3
import os
import sys

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

db_path = 'data/map_styles.db'
print('Exists:', os.path.exists(db_path), 'Size:', os.path.getsize(db_path))

conn = sqlite3.connect(db_path)
cur = conn.cursor()

# Check journal mode without setting it
cur.execute('PRAGMA journal_mode;')
print('journal_mode:', cur.fetchone()[0])

cur.execute('PRAGMA foreign_keys = ON;')
cur.execute('PRAGMA foreign_keys;')
print('foreign_keys enabled:', cur.fetchone()[0])

cur.execute('PRAGMA integrity_check;')
print('integrity_check:', cur.fetchall())

cur.execute('PRAGMA foreign_key_check;')
print('foreign_key_check:', cur.fetchall())

# Counts
for t in ['map_styles', 'map_style_tiles', 'map_style_props']:
    cur.execute(f"SELECT count(*) FROM {t}")
    print(f"{t} count:", cur.fetchone()[0])

# Biome codes and legacy aliases
cur.execute("SELECT biome_code, style_id, name_vi, name_en, legacy_alias FROM map_styles ORDER BY biome_code ASC")
print("\nBiome codes and legacy mappings:")
expected_legacies = {
    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 row in cur.fetchall():
    b_code, s_id, n_vi, n_en, leg_alias = row
    print(f"  Code {b_code:2d}: {s_id} | {n_vi} ({n_en}) | legacy: {leg_alias}")
    if b_code in expected_legacies:
        exp_alias, exp_style = expected_legacies[b_code]
        assert leg_alias == exp_alias, f"Code {b_code} legacy mismatch: expected {exp_alias}, got {leg_alias}"
        assert s_id == exp_style, f"Code {b_code} style mismatch: expected {exp_style}, got {s_id}"
    else:
        assert leg_alias is None, f"Code {b_code} expected None legacy alias, got {leg_alias}"

print("\nLegacy biome backward compatibility check PASSED!")

# Check tile mapping distribution
cur.execute("SELECT style_id, count(*) FROM map_style_tiles GROUP BY style_id")
tile_counts = cur.fetchall()
assert len(tile_counts) == 30, f"Expected 30 styles in tiles, got {len(tile_counts)}"
for s_id, cnt in tile_counts:
    assert cnt == 20, f"Style {s_id} has {cnt} tiles, expected 20"

# Verify all tile codes 0..19 are present for each style
cur.execute("SELECT style_id, group_concat(tile_type_id) FROM map_style_tiles GROUP BY style_id")
for s_id, code_list in cur.fetchall():
    codes = sorted([int(c) for c in code_list.split(',')])
    assert codes == list(range(20)), f"Style {s_id} missing tile codes: {codes}"

print("All 30 styles have exactly tile types 0..19!")

# Check props per style
cur.execute("SELECT style_id, count(*) FROM map_style_props GROUP BY style_id")
prop_counts = cur.fetchall()
assert len(prop_counts) == 30, f"Expected 30 styles in props, got {len(prop_counts)}"
for s_id, cnt in prop_counts:
    assert cnt >= 3, f"Style {s_id} has {cnt} props, expected >= 3"

print("All 30 styles have >= 3 props!")

conn.close()
