                 user: User = Depends(get_current_user),
                 _: None = Depends(require_csrf)):
    c = await _get_own(db, user, cid)
    if c.status != "paused":
        raise HTTPException(status_code=409, detail=f"Cannot resume a {c.status} campaign")
    res = await resume_campaign(db, c)
    if not res.get("ok"):
        raise HTTPException(status_code=409, detail=res.get("reason", "Cannot resume"))
    await log_audit(db, user.id, "campaign.resume", "campaign", c.id, {})
    return {"status": "running", "queued": res.get("queued")}


@router.post("/{cid}/cancel")
async def cancel(cid: int, db: AsyncSession = Depends(get_db),
                 user: User = Depends(get_current_user),
                 _: None = Depends(require_csrf)):
    c = await _get_own(db, user, cid)
    if c.status not in ("running", "paused", "queued", "draft"):
        raise HTTPException(status_code=409, detail=f"Cannot cancel a {c.status} campaign")
    res = await cancel_campaign(db, c)
    await log_audit(db, user.id, "campaign.cancel", "campaign", c.id, {})
    return {"status": "cancelled"}


# ---------------------------------------------------------------------------
# Monitor: progress, SSE stream, recipient table
# ---------------------------------------------------------------------------

async def _progress_payload(db: AsyncSession, c: Campaign) -> dict:
    """Live counters for the monitor: campaign fields + per-status breakdown."""
    breakdown = (await db.execute(
        select(CampaignRecipient.status, func.count())
        .where(CampaignRecipient.campaign_id == c.id)
        .group_by(CampaignRecipient.status))).all()
    counts = {s: int(n) for s, n in breakdown}
    jobs_agg = (await db.execute(
        select(func.count()).select_from(SendJob).where(SendJob.campaign_id == c.id)
    )).scalar() or 0
    done = counts.get("sent", 0) + counts.get("perm_failed", 0) + counts.get("suppressed", 0) + counts.get("skipped", 0)
    total = c.total_recipients or 0
    return {
        "campaign_id": c.id, "status": c.status, "total": total,
        "sent": counts.get("sent", 0), "temp_failed": counts.get("temp_failed", 0),
        "perm_failed": counts.get("perm_failed", 0),
        "suppressed": counts.get("suppressed", 0), "skipped": counts.get("skipped", 0),
        "pending": counts.get("pending", 0), "queued": counts.get("queued", 0),
        "processing": counts.get("processing", 0),
        "jobs_total": int(jobs_agg), "completed": done >= total and total > 0 and c.status in ("completed",),
        "progress_pct": round(100.0 * done / total, 1) if total else 0.0,
        "started_at": c.started_at.isoformat() if c.started_at else None,
        "finished_at": c.finished_at.isoformat() if c.finished_at else None,
    }


@router.get("/{cid}/progress")
async def get_progress(cid: int, user: User = Depends(get_current_user),
                       db: AsyncSession = Depends(get_db)):
    c = await _get_own(db, user, cid)
    return await _progress_payload(db, c)


@router.get("/{cid}/stream")
async def campaign_stream(cid: int, request: Request,
                          user: User = Depends(get_current_user),
                          db: AsyncSession = Depends(get_db)):
    """SSE live progress stream. Manual implementation (no sse-starlette): a Redis
    pub/sub subscription on campaign:{id}:progress plus periodic DB polling fallback.
    Emits event: progress with counters; event: done when campaign finishes."""
    c = await _get_own(db, user, cid)

    import redis.asyncio as aioredis
    from app.db.session import AsyncSessionLocal

    async def event_gen():
        r = aioredis.Redis.from_url(cfg.REDIS_URL, decode_responses=True)
        pubsub = r.pubsub()
        channel = f"campaign:{cid}:progress"
        await pubsub.subscribe(channel)
        heartbeat = 2.0
        poll_interval = 5.0
        last_payload = None
        last_poll = 0.0
        import time
        try:
            yield "event: connected\ndata: {\"ok\": true}\n\n"
            while True:
                if await request.is_disconnected():
                    break
                # check for pub/sub tick (non-blocking)
                msg = await pubsub.get_message(ignore_subscribe_messages=True, timeout=0.1)
                now = time.monotonic()
                payload = None
                if msg is not None or now - last_poll >= poll_interval:
                    # refresh counters from DB with a fresh session
                    async with AsyncSessionLocal() as s:
                        camp = await s.get(Campaign, cid)
                        if camp:
                            payload = await _progress_payload(s, camp)
                    last_poll = now
                if payload is None and msg is None and now - last_poll < poll_interval:
                    await asyncio.sleep(heartbeat)
                    yield ": keepalive\n\n"
                    continue
                if payload:
                    data = json.dumps(payload)
                    if data != last_payload or msg is not None:
                        yield f"event: progress\ndata: {data}\n\n"
                        last_payload = data
                    if payload.get("status") in ("completed", "cancelled", "failed"):
                        yield f"event: done\ndata: {json.dumps(payload)}\n\n"
                        break
                await asyncio.sleep(0.2)
        finally:
            try:
                await pubsub.unsubscribe(channel)
                await pubsub.close()
                await r.aclose()
            except Exception:
                pass

    return StreamingResponse(event_gen(), media_type="text/event-stream",
                             headers={"Cache-Control": "no-cache",
                                      "X-Accel-Buffering": "no",
                                      "Connection": "keep-alive"})


@router.get("/{cid}/recipients")
async def campaign_recipients(cid: int, status: str = Query(""),
                              search: str = Query(""),
                              page: int = Query(1, ge=1),
                              page_size: int = Query(50, ge=1, le=200),
                              db: AsyncSession = Depends(get_db),
                              user: User = Depends(get_current_user)):
    """Monitor table: per-recipient status, assigned account, subject/template, errors."""
    c = await _get_own(db, user, cid)
    q = select(CampaignRecipient).where(CampaignRecipient.campaign_id == cid)
    if status:
        q = q.where(CampaignRecipient.status == status)
    if search:
        q = q.where(CampaignRecipient.email.ilike(f"%{search}%"))
    total = (await db.execute(select(func.count()).select_from(q.subquery()))).scalar() or 0
    rows = (await db.execute(q.order_by(CampaignRecipient.seq)
                             .offset((page - 1) * page_size).limit(page_size))).scalars().all()

    async def names():
        acc_map, subj_map, tpl_map = {}, {}, {}
        for cr in rows:
            if cr.assigned_account_id and cr.assigned_account_id not in acc_map:
                a = await db.get(GmailAccount, cr.assigned_account_id)
                acc_map[cr.assigned_account_id] = a.email if a else "?"
            if cr.generated_subject_id and cr.generated_subject_id not in subj_map:
                s = await db.get(SubjectLine, cr.generated_subject_id)
                subj_map[cr.generated_subject_id] = (s.subject[:80] if s else "?")
            if cr.generated_template_id and cr.generated_template_id not in tpl_map:
                t = await db.get(EmailTemplate, cr.generated_template_id)
                tpl_map[cr.generated_template_id] = (t.name if t else "?")
        return acc_map, subj_map, tpl_map

    acc_map, subj_map, tpl_map = await names()
    out = []
    for cr in rows:
        out.append({
            "id": cr.id, "seq": cr.seq, "email": cr.email, "status": cr.status,
            "account": acc_map.get(cr.assigned_account_id, ""),
            "subject": subj_map.get(cr.generated_subject_id, ""),
            "template": tpl_map.get(cr.generated_template_id, ""),
            "invoice_number": cr.generated_invoice_number,
            "amount": cr.generated_amount, "shipping": cr.generated_shipping,
            "attempts": cr.attempt_count, "message_id": cr.msg_id,
            "thread_id": cr.thread_id,
            "sent_at": cr.sent_at.isoformat() if cr.sent_at else None,
            "last_error": (cr.last_error or "")[:200],
        })
    return {"recipients": out, "total": total, "page": page, "page_size": page_size}


@router.get("/{cid}/export")
async def export_campaign(cid: int, db: AsyncSession = Depends(get_db),
                          user: User = Depends(get_current_user)):
    """CSV export of campaign results (one row per campaign recipient)."""
    c = await _get_own(db, user, cid)
    rows = (await db.execute(
        select(CampaignRecipient).where(CampaignRecipient.campaign_id == cid)
        .order_by(CampaignRecipient.seq))).scalars().all()

    def generate():
        buf = io.StringIO()
        w = csv.writer(buf)
        w.writerow(["seq", "email", "status", "account", "subject", "template",
                    "invoice_number", "amount", "shipping", "attempts",
                    "message_id", "thread_id", "sent_at", "last_error"])
        yield buf.getvalue()
        buf.seek(0); buf.truncate(0)
        for cr in rows:
            w.writerow([cr.seq, cr.email, cr.status, cr.assigned_account_id,
                        cr.generated_subject_id, cr.generated_template_id,
                        cr.generated_invoice_number, cr.generated_amount or "",
                        cr.generated_shipping or "", cr.attempt_count,
                        cr.msg_id, cr.thread_id,
                        cr.sent_at.isoformat() if cr.sent_at else "",
                        (cr.last_error or "")[:300]])
