#!/usr/bin/env python3
"""Create or update the E2E test admin user in the auth SQLite DB.

This script is invoked by Playwright's ``globalSetup`` (via ``global-setup.ts``)
before any test runs. It ensures the auth DB schema exists and that a test
admin user with known credentials is present.

The user credentials default to:
    username: e2e_test_admin
    password: E2eTestPass123!
    email:    e2e-test@agentkit.local
    role:     admin

Override via environment variables ``E2E_TEST_USERNAME``, ``E2E_TEST_PASSWORD``,
``E2E_TEST_EMAIL`` if needed.

Exit codes:
    0 — user created or updated successfully
    1 — unexpected error
"""

from __future__ import annotations

import asyncio
import os
import sys
import uuid
from datetime import datetime, timezone
from pathlib import Path

# Resolve project root so we can import agentkit regardless of CWD.
# This file lives at src/agentkit/server/frontend/e2e/setup-test-user.py
_PROJECT_ROOT = Path(__file__).resolve().parents[3]
_SRC_ROOT = _PROJECT_ROOT / "src"
if str(_SRC_ROOT) not in sys.path:
    sys.path.insert(0, str(_SRC_ROOT))

import aiosqlite  # noqa: E402

from agentkit.server.auth.models import DEFAULT_AUTH_DB_PATH, init_auth_db  # noqa: E402
from agentkit.server.auth.password import hash_password  # noqa: E402

TEST_USERNAME = os.environ.get("E2E_TEST_USERNAME", "e2e_test_admin")
TEST_PASSWORD = os.environ.get("E2E_TEST_PASSWORD", "E2eTestPass123!")
TEST_EMAIL = os.environ.get("E2E_TEST_EMAIL", "e2e-test@example.com")


async def ensure_test_user() -> None:
    db_path = DEFAULT_AUTH_DB_PATH
    # Create schema (idempotent) — mirrors what /auth/login does on first hit.
    await init_auth_db(db_path)

    password_hash = hash_password(TEST_PASSWORD)
    now_iso = datetime.now(timezone.utc).isoformat()

    async with aiosqlite.connect(str(db_path)) as db:
        cursor = await db.execute("SELECT id FROM users WHERE username = ?", (TEST_USERNAME,))
        existing = await cursor.fetchone()

        if existing:
            # Update password + ensure admin role + terminal authorization
            await db.execute(
                "UPDATE users SET password_hash = ?, role = 'admin', is_active = 1, "
                "is_terminal_authorized = 1, is_server_terminal_authorized = 1, "
                "email = ?, updated_at = ? WHERE username = ?",
                (password_hash, TEST_EMAIL, now_iso, TEST_USERNAME),
            )
            await db.commit()
            print(f"[setup-test-user] Updated existing test user '{TEST_USERNAME}'")
        else:
            user_id = str(uuid.uuid4())
            await db.execute(
                "INSERT INTO users (id, username, email, password_hash, role, "
                "is_active, is_terminal_authorized, is_server_terminal_authorized, "
                "created_at, updated_at) VALUES (?, ?, ?, ?, 'admin', 1, 1, 1, ?, ?)",
                (user_id, TEST_USERNAME, TEST_EMAIL, password_hash, now_iso, now_iso),
            )
            await db.commit()
            print(f"[setup-test-user] Created test admin user '{TEST_USERNAME}'")


def main() -> int:
    try:
        asyncio.run(ensure_test_user())
        return 0
    except Exception as exc:  # noqa: BLE001
        print(f"[setup-test-user] ERROR: {exc}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
