        raise HTTPException(status_code=400, detail="Campaign has no recipient list")
    rl = await db.get(RecipientList, c.recipient_list_id)
    if not rl or rl.user_id != user.id:
        raise HTTPException(status_code=400, detail="Recipient list not found")

    recipient_rows = (await db.execute(
        select(Recipient).where(Recipient.list_id == rl.id, Recipient.is_valid == True)  # noqa: E712
        .order_by(Recipient.id).limit(size))).scalars().all()
    if not recipient_rows:
        raise HTTPException(status_code=400, detail="Recipient list has no valid recipients")

    # materialize plan rows WITHOUT persisting CampaignRecipient entities
    result = await materialize_campaign(db, c, recipient_rows, preview=True,
                                          preview_size=size)
    plan = result.get("plan", [])

    # render actual message content per sample
    engine = VariableEngine(c.variable_config or {})
    out = []
    for item in plan:
        rec = next((r for r in recipient_rows if r.id == item["recipient_id"]), None)
        if not rec:
            continue
        tpl = await db.get(EmailTemplate, item["template_id"]) if item.get("template_id") else None
        subj = await db.get(SubjectLine, item["subject_id"]) if item.get("subject_id") else None
        g = GeneratedValues()
        g.invoice_number = item.get("invoice_number", "")
        g.amount = item.get("amount")
        g.shipping = item.get("shipping")
        g.invoice_date = item.get("invoice_date")
        g.due_date = item.get("due_date")
        phone = item.get("phone", "")
        unsub = f"{cfg.UNSUBSCRIBE_BASE or cfg.BASE_URL}/unsubscribe/{rec.unsub_token}" if c.unsubscribe_enabled else ""
        extra = {"unsubscribe_link": unsub, "company_phone": phone}

        body_html = ""
        subject = ""
        warn_list = list(item.get("warnings") or []) if isinstance(item.get("warnings"), list) else ([item["warnings"]] if item.get("warnings") else [])
        if tpl:
            res = engine.substitute(tpl.body_html, rec, g,
                                    custom_fields=rec.custom_fields or {}, extra=extra)
            body_html = res.text
            subject = subj.subject if subj else (tpl.subject_hint or tpl.name)
            for u in res.unknown:
                warn_list.append(f"Unknown variable in body: {u}")
            for m_ in res.missing:
                warn_list.append(f"Missing data for: {m_}")
        if subj:
            res_s = engine.substitute(subj.subject, rec, g,
                                      custom_fields=rec.custom_fields or {}, extra=extra)
            subject = res_s.text
            for u in res_s.unknown:
                warn_list.append(f"Unknown variable in subject: {u}")
            for m_ in res_s.missing:
                warn_list.append(f"Missing data in subject: {m_}")
        out.append({
            "recipient": {"id": rec.id, "email": rec.email,
                          "first_name": rec.first_name, "last_name": rec.last_name},
            "from_account": item.get("account", ""),
            "subject": subject,
            "body_html": sanitize_preview(body_html),
            "raw_variables": {"invoice_number": g.invoice_number,
                              "amount": g.amount, "shipping": g.shipping,
                              "phone": phone},
            "warnings": warn_list,
        })
    return {"campaign_id": c.id, "sample_size": len(out), "messages": out,
            "plan_summary": result.get("summary", {})}


# ---------------------------------------------------------------------------
# Control: start / pause / resume / cancel
# ---------------------------------------------------------------------------

@router.post("/{cid}/start")
async def start(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 == "draft":
        # materialize campaign_recipients on first start
        if not c.recipient_list_id:
            raise HTTPException(status_code=400, detail="Campaign has no recipient list")
        rl = await db.get(RecipientList, c.recipient_list_id)
        if not rl:
            raise HTTPException(status_code=400, detail="Recipient list not found")
        recipient_rows = (await db.execute(
            select(Recipient).where(Recipient.list_id == c.recipient_list_id,
                                    Recipient.is_valid == True)  # noqa: E712
            .order_by(Recipient.id))).scalars().all()
        if not recipient_rows:
            raise HTTPException(status_code=400, detail="No valid recipients in list")
        if len(recipient_rows) > cfg.MAX_RECIPIENTS_PER_CAMPAIGN:
            raise HTTPException(status_code=400,
                                detail=f"Too many recipients ({len(recipient_rows)}); max {cfg.MAX_RECIPIENTS_PER_CAMPAIGN}")
        result = await materialize_campaign(db, c, recipient_rows)
        c.total_recipients = result.get("total", 0)
        await db.commit()
    res = await start_campaign(db, c)
    if not res.get("ok"):
        raise HTTPException(status_code=409, detail=res.get("reason", "Cannot start"))
    await log_audit(db, user.id, "campaign.start", "campaign", c.id,
                    {"queued": res.get("queued")})
    return {"status": "running", "queued": res.get("queued")}


@router.post("/{cid}/pause")
async def pause(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 != "running":
        raise HTTPException(status_code=409, detail=f"Cannot pause a {c.status} campaign")
    res = await pause_campaign(db, c)
    await log_audit(db, user.id, "campaign.pause", "campaign", c.id, {})
    return {"status": "paused"}


@router.post("/{cid}/resume")
async def resume(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 != "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),
