#!/usr/bin/env python3
"""
Seed test data for Playwright E2E tests.
Creates a test user and sample memos if they don't exist.
"""
import os
import asyncio
import httpx

BACKEND_URL = os.getenv("BACKEND_URL", "http://backend:5000")
TEST_USER = {
    "email": "test@example.com",
    "password": "testpassword123",
    "username": "testuser",
}

async def signup_user():
    """Create test user via signup API."""
    async with httpx.AsyncClient() as client:
        try:
            response = await client.post(
                f"{BACKEND_URL}/api/v1/auth/signup",
                json={
                    "email": TEST_USER["email"],
                    "password": TEST_USER["password"],
                    "username": TEST_USER["username"],
                }
            )
            if response.status_code in (200, 201):
                print(f"✅ Created test user: {TEST_USER['email']}")
                data = response.json()
                return data.get("token") or data.get("access_token")
            elif response.status_code == 409:
                print(f"ℹ️  Test user already exists, signing in...")
                # Try to sign in
                resp = await client.post(
                    f"{BACKEND_URL}/api/v1/auth/signin",
                    json={
                        "email": TEST_USER["email"],
                        "password": TEST_USER["password"],
                    }
                )
                if resp.status_code == 200:
                    data = resp.json()
                    print(f"✅ Signed in as test user")
                    return data.get("token") or data.get("access_token")
                else:
                    print(f"❌ Failed to sign in: {resp.status_code}")
            else:
                print(f"❌ Signup failed: {response.status_code} - {response.text}")
        except Exception as e:
            print(f"❌ Error signing up: {e}")
    return None

async def create_sample_memos(token: str):
    """Create a few sample memos for testing."""
    headers = {"Authorization": f"Bearer {token}"}
    async with httpx.AsyncClient(headers=headers) as client:
        memo_contents = [
            "This is a test memo for Playwright E2E tests.",
            "Another test memo with some content.",
            "Third memo - testing comment functionality.",
        ]
        for content in memo_contents:
            try:
                response = await client.post(
                    f"{BACKEND_URL}/api/v1/memos",
                    json={"content": content, "visibility": "PUBLIC"}
                )
                if response.status_code in (200, 201):
                    print(f"✅ Created memo: {content[:30]}...")
                elif response.status_code == 409:
                    print(f"ℹ️  Memo already exists: {content[:30]}...")
                else:
                    print(f"❌ Failed to create memo: {response.status_code}")
            except Exception as e:
                print(f"❌ Error creating memo: {e}")

async def main():
    print("🌱 Seeding test data...")
    token = await signup_user()
    if token:
        await create_sample_memos(token)
        print("✅ Test data seeding complete!")
    else:
        print("❌ Failed to get auth token, skipping memo creation")

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