"""Run pytest and save results to file."""
import sys
import os
import subprocess

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

# First ensure test deps are installed
try:
    import pytest
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install", "pytest", "pytest-asyncio", "aiosqlite", "-q"])

try:
    import httpx
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install", "httpx", "-q"])

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

output = f"=== STDOUT ===\n{result.stdout}\n\n=== STDERR ===\n{result.stderr}\n\n=== RC: {result.returncode} ==="
print(output)

with open(r"C:\Users\simon\wecom_it_smart_desk\backend\test_results.txt", "w", encoding="utf-8") as f:
    f.write(output)
