#!/usr/bin/env python3
"""
E2E Test Setup: Ensure test user 'e2etest' exists in SQLite DB.
Run before Playwright tests.
"""
import sys
import os
import asyncio

# Add backend to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

async def setup():
    from common.sqlite_client import init_sqlite, get_sqlite
    await init_sqlite()
    db = await get_sqlite()

    # Check if e2etest user exists
    row = await db.fetchone("SELECT id, username FROM cuccu_users WHERE username = ?", ("e2etest",))
    if row:
        print(f"[OK] Test user 'e2etest' already exists (id={row['id']})")
        return

    # Create the user with bcrypt password
    import hashlib, uuid
    from datetime import datetime
    try:
        from passlib.context import CryptContext
        ctx = CryptContext(schemes=["bcrypt"])
        hashed = ctx.hash("Test12345!")
    except Exception:
        # Fallback: sha256 (less ideal but works for testing)
        hashed = hashlib.sha256("Test12345!".encode()).hexdigest()

    user_id = str(uuid.uuid4())
    now = datetime.utcnow().isoformat()

    await db.execute(
        """INSERT INTO cuccu_users (id, username, email, password_hash, role, created_at, updated_at)
           VALUES (?, ?, ?, ?, ?, ?, ?)
           ON CONFLICT(username) DO NOTHING""",
        (user_id, "e2etest", "e2etest@test.local", hashed, "USER", now, now),
    )
    print("[OK] Created test user 'e2etest' with password 'Test12345!'")

if __name__ == "__main__":
    asyncio.run(setup())
