@router.get("/{template_id}")
async def get_template(template_id: int, user: User = Depends(get_current_user),
                       db: AsyncSession = Depends(get_db)):
    t = await db.get(EmailTemplate, template_id)
    if not t or t.user_id != user.id:
        raise HTTPException(404, "Not found")
    analysis = analyze_template_variables(t.body_html)
    return {"id": t.id, "name": t.name, "subject_hint": t.subject_hint,
            "body_html": t.body_html, "body_text": t.body_text,
            "variables": analysis["variables"], "unknown_variables": analysis["unknown"]}


@router.put("/{template_id}")
async def edit_template(template_id: int, payload: TemplateIn,
                        user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
    t = await db.get(EmailTemplate, template_id)
    if not t or t.user_id != user.id:
        raise HTTPException(404, "Not found")
    if re.search(r"<script", payload.body_html, re.I):
        raise HTTPException(400, "Script tags are not allowed")
    t.name = payload.name[:250]
    t.body_html = payload.body_html
    t.body_text = payload.body_text
    t.subject_hint = payload.subject_hint[:500]
    await db.commit()
    return {"ok": True}


@router.post("/{template_id}/duplicate")
async def duplicate_template(template_id: int, user: User = Depends(get_current_user),
                             db: AsyncSession = Depends(get_db)):
    t = await db.get(EmailTemplate, template_id)
    if not t or t.user_id != user.id:
        raise HTTPException(404, "Not found")
    row = EmailTemplate(user_id=user.id, name=f"{t.name} (copy)", body_html=t.body_html,
                        body_text=t.body_text, subject_hint=t.subject_hint, source=t.source)
    db.add(row)
    await db.commit()
    return {"id": row.id}


@router.delete("/{template_id}")
async def delete_template(template_id: int, user: User = Depends(get_current_user),
                          db: AsyncSession = Depends(get_db)):
    t = await db.get(EmailTemplate, template_id)
    if not t or t.user_id != user.id:
        raise HTTPException(404, "Not found")
    await db.delete(t)
    await db.commit()
    return {"ok": True}


@router.post("/clear-all")
async def clear_all(user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
    await db.execute(sa_delete(EmailTemplate).where(EmailTemplate.user_id == user.id))
    await db.commit()
    return {"ok": True}


@router.post("/{template_id}/preview")
async def preview_template(template_id: int, sample: dict = {},
                           user: User = Depends(get_current_user),
                           db: AsyncSession = Depends(get_db)):
    """Render template with sample data (sanitized) and run validation."""
    t = await db.get(EmailTemplate, template_id)
    if not t or t.user_id != user.id:
        raise HTTPException(404, "Not found")
    from app.services.variable_engine import GeneratedValues, VariableEngine
    engine = VariableEngine(sample.get("config", {}))
    g = GeneratedValues(
        invoice_number=engine.generate_invoice_number(set()),
        amount=engine.generate_amount(), shipping=engine.generate_shipping(),
        random_name=engine.generate_random_name(),
        invoice_date=sample.get("invoice_date", "2026-01-15"),
        due_date=sample.get("due_date", "2026-01-30"),
        phone=sample.get("phone", "+1 555 000 0000"),
    )
    res = engine.substitute(t.body_html, sample.get("recipient", {
        "FirstName": "John", "LastName": "Smith", "CompanyName": "Example Corp",
        "CustomerEmail": "customer@example.com", "Email": "john@example.com"}),
        g, custom_fields=sample.get("custom_fields", {}),
        extra={"unsubscribe_link": "https://example.com/unsubscribe?token=sample"})
    problems = message_builder.validate_html(res.text)
    return {"rendered_html": message_builder.sanitize_preview(res.text),
            "unknown_variables": res.unknown, "missing_variables": res.missing,
            "warnings": problems,
            "generated": {"invoice_number": g.invoice_number, "amount": g.amount,
                          "shipping": g.shipping}}


@router.post("/{template_id}/test-pdf")
async def test_pdf(template_id: int, sample: dict = {},
                   user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
    """Real HTML->PDF conversion test; returns the PDF inline."""
    t = await db.get(EmailTemplate, template_id)
    if not t or t.user_id != user.id:
        raise HTTPException(404, "Not found")
    from app.services.variable_engine import GeneratedValues, VariableEngine
    engine = VariableEngine(sample.get("config", {}))
    g = GeneratedValues(invoice_number=engine.generate_invoice_number(set()),
                        amount=engine.generate_amount(), shipping=engine.generate_shipping(),
                        invoice_date=sample.get("invoice_date", "2026-01-15"),
                        due_date=sample.get("due_date", "2026-01-30"))
    res = engine.substitute(t.body_html, sample.get("recipient", {}), g,
                            extra={"unsubscribe_link": "https://example.com/unsubscribe"})
    pdf = message_builder.html_to_pdf(res.text)
    import base64
    return {"pdf_base64": base64.b64encode(pdf).decode(), "size_bytes": len(pdf),
            "engine": "WeasyPrint"}
