"""
Seed dev accounts for local development. Idempotent — safe to run multiple times.

Creates four fixed accounts so you can test every access tier immediately:

  admin@beanflows.coffee   — admin role, free plan
  trader@beanflows.coffee  — free plan (no subscription)
  starter@beanflows.coffee — active starter subscription
  pro@beanflows.coffee     — active pro subscription

Login via: http://localhost:5001/auth/dev-login?email=<email>
"""
import asyncio
from datetime import datetime, timedelta

from .core import close_db, execute, fetch_one, init_db

# email, role (or None), plan (or None for free)
ACCOUNTS = [
    ("admin@beanflows.coffee",   "admin",  None),
    ("trader@beanflows.coffee",  None,     None),
    ("starter@beanflows.coffee", None,     "starter"),
    ("pro@beanflows.coffee",     None,     "pro"),
]


async def _upsert_user(email: str) -> int:
    row = await fetch_one("SELECT id FROM users WHERE email = ?", (email,))
    if row:
        return row["id"]
    now = datetime.utcnow().isoformat()
    return await execute(
        "INSERT INTO users (email, created_at) VALUES (?, ?)",
        (email, now),
    )


async def _upsert_subscription(user_id: int, plan: str) -> None:
    now = datetime.utcnow().isoformat()
    period_end = (datetime.utcnow() + timedelta(days=365)).isoformat()
    existing = await fetch_one(
        "SELECT id FROM subscriptions WHERE user_id = ?", (user_id,)
    )
    if existing:
        await execute(
            "UPDATE subscriptions SET plan = ?, status = 'active', current_period_end = ? WHERE user_id = ?",
            (plan, period_end, user_id),
        )
    else:
        await execute(
            """INSERT INTO subscriptions (user_id, plan, status, current_period_end, created_at)
               VALUES (?, ?, 'active', ?, ?)""",
            (user_id, plan, period_end, now),
        )


async def seed() -> None:
    await init_db()
    for email, role, plan in ACCOUNTS:
        user_id = await _upsert_user(email)
        if role:
            await execute(
                "INSERT OR IGNORE INTO user_roles (user_id, role) VALUES (?, ?)",
                (user_id, role),
            )
        if plan:
            await _upsert_subscription(user_id, plan)
        tag = f"[{role or plan or 'free'}]"
        print(f"  {email} {tag}")
    await close_db()


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