"""Seed demo data for local end-to-end QA: subjects, template, authorized Gmail
account (with fake token — sends will fail at the Gmail API boundary, which is
exactly what we want to observe in the monitor), recipient list exists already.

Run: python3 scripts/seed_demo.py
"""
import asyncio
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from sqlalchemy import select  # noqa: E402

from app.db.session import AsyncSessionLocal  # noqa: E402
from app.models import (  # noqa: E402
    Campaign, EmailTemplate, GmailAccount, OAuthToken, RecipientList, SubjectLine, User,
)

DEMO_EMAIL = "tester@example.com"

SUBJECTS = [
    "Invoice %RandomInvoiceNumber% for %CompanyName%",
    "Payment reminder for %FirstName%",
    "Balance due: %RandomTotal% — due %DueDate%",
]

TPL_HTML = """<!DOCTYPE html>
<html><body style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto">
  <h2 style="color:#1a73e8">Invoice %RandomInvoiceNumber%</h2>
  <p>Dear %FirstName% %LastName%,</p>
  <p>Your invoice <b>%RandomInvoiceNumber%</b> for <b>%RandomTotal%</b> (shipping
  %RandomShippingCharge%) is due on %DueDate%.</p>
  <p>Company: %CompanyName% &middot; Phone: %CompanyPhone%</p>
  <p style="font-size:12px;color:#666">Prefer plain text? The plain-text alternative is attached automatically.</p>
  <p style="font-size:12px"><a href="%UnsubscribeLink%">Unsubscribe</a></p>
</body></html>"""


async def main():
    async with AsyncSessionLocal() as db:
        user = (await db.execute(select(User).where(User.email == DEMO_EMAIL))).scalar_one_or_none()
        if not user:
            print(f"ERROR: user {DEMO_EMAIL} not found — register it first")
            return
        # clean previous demo rows
        for T in (SubjectLine, EmailTemplate):
            for row in (await db.execute(select(T).where(T.user_id == user.id))).scalars():
                await db.delete(row)
        accs = (await db.execute(select(GmailAccount).where(GmailAccount.user_id == user.id))).scalars().all()
        for a in accs:
            await db.delete(a)
        await db.commit()

        for s in SUBJECTS:
            db.add(SubjectLine(user_id=user.id, subject=s))
        db.add(EmailTemplate(user_id=user.id, name="QA Invoice — blue",
                             subject_hint="Invoice %RandomInvoiceNumber% for %CompanyName%",
                             body_html=TPL_HTML))
        acc = GmailAccount(user_id=user.id, email="qa.bot.sender@gmail.com",
                           status="authorized", sending_method="api", is_active=True,
                           daily_limit=200, campaign_limit=200)
        db.add(acc)
        await db.commit()
        db.add(OAuthToken(account_id=acc.id, access_token="fake-token-for-local-qa",
                          refresh_token="fake-refresh",
                          expires_at=datetime.now(timezone.utc) + timedelta(hours=2)))
        await db.commit()
        counts = {}
        counts["subjects"] = (await db.execute(select(SubjectLine).where(SubjectLine.user_id == user.id))).scalars()
        counts["templates"] = (await db.execute(select(EmailTemplate).where(EmailTemplate.user_id == user.id))).scalars()
        counts["accounts"] = (await db.execute(select(GmailAccount).where(GmailAccount.user_id == user.id))).scalars()
        print("Seeded for", DEMO_EMAIL,
              "| subjects:", len(list(counts["subjects"])),
              "| templates:", len(list(counts["templates"])),
              "| accounts:", len(list(counts["accounts"])))


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