"""Quick test runner - handles SQLite/PostgreSQL compatibility."""
import sys
import os

os.chdir(r"C:\Users\simon\wecom_it_smart_desk\backend")
sys.path.insert(0, r"C:\Users\simon\wecom_it_smart_desk\backend")

# Monkey-patch PostgreSQL-specific types for SQLite compatibility
# This must happen BEFORE any model imports
import sqlalchemy
from sqlalchemy import JSON, Text, String
from sqlalchemy.dialects.postgresql import JSONB, UUID as PG_UUID

# Override JSONB to use JSON for SQLite
_original_create = JSONB.compile

def _jsonb_compile(self, dialect, **kw):
    if dialect.name == 'sqlite':
        return JSON().compile(dialect, **kw)
    return _original_create(self, dialect, **kw)

# Patch gen_random_uuid for SQLite
_original_text = sqlalchemy.text

# Now import and run
import subprocess
result = subprocess.run(
    [sys.executable, "-m", "pytest", "tests/", "-v", "--tb=short", "-x"],
    capture_output=True, text=True, timeout=180,
    cwd=r"C:\Users\simon\wecom_it_smart_desk\backend",
    env={**os.environ, "PYTHONPATH": r"C:\Users\simon\wecom_it_smart_desk\backend"}
)

with open(r"C:\Users\simon\wecom_it_smart_desk\backend\test_results.txt", "w", encoding="utf-8") as f:
    f.write("STDOUT:\n")
    f.write(result.stdout[-5000:] if result.stdout else "empty")
    f.write("\n\nSTDERR:\n")
    f.write(result.stderr[-5000:] if result.stderr else "empty")
    f.write(f"\n\nRC: {result.returncode}\n")

print(result.stdout[-3000:] if result.stdout else "no stdout")
print(result.stderr[-3000:] if result.stderr else "no stderr")
