import sqlite3
import sys
from pathlib import Path

# Add project root to sys.path
project_root = Path(__file__).resolve().parent.parent.parent.parent
sys.path.insert(0, str(project_root))

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

from server.world.map_style_service import MapStyleService
from server.world.map_style_types import MapStyleDefinition

print("=== ADVERSARIAL STRESS TEST: MapStyleService ===")

# Test 1: Proof of Real SQL Execution (Dynamic mutation test)
print("\n[Stress Test 1] Verifying Dynamic Database Query Execution...")
mem_service = MapStyleService(db_path=":memory:")

# Mutate a record directly in SQLite
with mem_service._get_connection() as conn:
    conn.execute(
        "UPDATE map_styles SET name_vi = 'AUDITOR_MUTATED_NAME' WHERE style_id = 'STY_01_HOANG_MANG_CO_LO'"
    )

fetched = mem_service.get_style("STY_01_HOANG_MANG_CO_LO")
assert fetched is not None, "Failed to fetch style"
assert fetched.name_vi == "AUDITOR_MUTATED_NAME", (
    f"FACADE DETECTED! Expected 'AUDITOR_MUTATED_NAME', got '{fetched.name_vi}'. "
    "Service returned static memory data instead of querying database!"
)
print("  -> PASS: Service queried SQLite directly and reflected mutated database record.")

# Test 2: SQL Injection resilience
print("\n[Stress Test 2] SQL Injection Safety...")
sqli_attempts = [
    "' OR 1=1 --",
    "STY_01_HOANG_MANG_CO_LO' OR '1'='1",
    "'; DROP TABLE map_styles; --",
    "1 UNION SELECT * FROM map_styles",
]
for payload in sqli_attempts:
    res = mem_service.get_style(payload)
    assert res is None, f"SQL Injection anomaly with payload: {payload}"
    res_code = mem_service.get_style_by_code(999999)
    assert res_code is None
print("  -> PASS: Parameterized queries safely reject SQL injection payloads.")

# Test 3: Boundary inputs (biome_code & tile_code)
print("\n[Stress Test 3] Boundary Conditions...")
assert mem_service.get_style_by_code(0) is None
assert mem_service.get_style_by_code(-1) is None
assert mem_service.get_style_by_code(31) is None
assert mem_service.get_style_by_code(256) is None

assert mem_service.get_tile_mapping("STY_01_HOANG_MANG_CO_LO", -1) is None
assert mem_service.get_tile_mapping("STY_01_HOANG_MANG_CO_LO", 20) is None
assert mem_service.get_tile_mapping("NON_EXISTENT_STYLE", 1) is None
print("  -> PASS: Boundary inputs return None cleanly without exceptions.")

# Test 4: Schema Constraint Enforcement
print("\n[Stress Test 4] Strict DB Constraints...")
with mem_service._get_connection() as conn:
    # 4a: Out of bounds biome_code in DB check
    try:
        conn.execute("INSERT INTO map_styles (style_id, biome_code, name_vi, name_en, theme_category, theme_category_name, description, floor_color_hex, wall_color_hex, path_color_hex, liquid_color_hex, ambient_light_hex, asset_dir, monster_family) VALUES ('BAD', 300, 'a', 'b', 'HOANG_DA_DA_NGOAI', 'c', 'd', '#111111', '#222222', '#333333', '#444444', '#555555', 'dir', 'm')")
        raise AssertionError("CHECK constraint on biome_code (1-255) failed to trigger!")
    except sqlite3.IntegrityError:
        pass

    # 4b: Invalid theme category
    try:
        conn.execute("INSERT INTO map_styles (style_id, biome_code, name_vi, name_en, theme_category, theme_category_name, description, floor_color_hex, wall_color_hex, path_color_hex, liquid_color_hex, ambient_light_hex, asset_dir, monster_family) VALUES ('BAD', 50, 'a', 'b', 'TIEN_HIEP_MAU_ME', 'c', 'd', '#111111', '#222222', '#333333', '#444444', '#555555', 'dir', 'm')")
        raise AssertionError("CHECK constraint on theme_category failed to trigger!")
    except sqlite3.IntegrityError:
        pass

    # 4c: Unique biome_code constraint
    try:
        conn.execute("INSERT INTO map_styles (style_id, biome_code, name_vi, name_en, theme_category, theme_category_name, description, floor_color_hex, wall_color_hex, path_color_hex, liquid_color_hex, ambient_light_hex, asset_dir, monster_family) VALUES ('DUPLICATE_CODE', 6, 'a', 'b', 'HOANG_DA_DA_NGOAI', 'c', 'd', '#111111', '#222222', '#333333', '#444444', '#555555', 'dir', 'm')")
        raise AssertionError("UNIQUE constraint on biome_code failed to trigger!")
    except sqlite3.IntegrityError:
        pass

print("  -> PASS: SQLite CHECK and UNIQUE constraints reject invalid data.")

# Test 5: Disk DB WAL and Pragma Verification
print("\n[Stress Test 5] Disk Database PRAGMA settings...")
disk_conn = sqlite3.connect('data/map_styles.db')
cur = disk_conn.cursor()
cur.execute("PRAGMA journal_mode")
j_mode = cur.fetchone()[0]
print(f"  journal_mode: {j_mode}")

cur.execute("PRAGMA synchronous")
sync = cur.fetchone()[0]
print(f"  synchronous: {sync}")

cur.execute("PRAGMA foreign_keys")
fk = cur.fetchone()[0]
print(f"  foreign_keys: {fk}")

disk_conn.close()
mem_service.close()

print("\nALL STRESS TESTS COMPLETED SUCCESSFULLY!")
