#!/usr/bin/env python3
"""Post-install: tickets + resend activation emails for approved registrations."""
import json
import sys

sys.path.insert(0, "/app")

from app import auth, desk_tickets, mail_notify, registration_store

DESK_URL = mail_notify.DESK_PUBLIC_URL


def main() -> None:
    with auth.db() as conn:
        rows = conn.execute(
            "SELECT * FROM desk_registration_requests WHERE status = 'approved' ORDER BY id"
        ).fetchall()
        pending = []
        for row in rows:
            r = dict(row)
            token = r.get("activation_token")
            url = f"{DESK_URL}/activate.html?token={token}" if token else None
            pending.append({"id": r["id"], "email": r["email"], "role": r.get("role"), "url": url})

            existing = conn.execute(
                "SELECT id FROM tickets WHERE payload LIKE ? LIMIT 1",
                (f'%"request_id": {r["id"]},%',),
            ).fetchone()
            if not existing and url:
                desk_tickets.ticket_registration_approved(
                    conn,
                    r["id"],
                    r["email"],
                    r["role"] or "technician",
                    url,
                    r.get("display_name"),
                )
                print(f"ticket activar: {r['email']}")

            if url:
                ok = mail_notify.notify_candidate_approved(r["email"], url, r["role"] or "technician")
                print(f"email {r['email']}: {'OK' if ok else 'FAIL'}")

        desk_tickets.ticket_postfix_ready(conn, pending)
        print("ticket root: Postfix VM122 activo")

    # Test SMTP
    ok = mail_notify.send_email(
        mail_notify.ROOT_NOTIFY_EMAIL,
        "[Ligbox Ops] Postfix VM122 activo",
        "Postfix na VM122 configurado. Relay interno VM112. Emails Desk operacionais.",
    )
    print(f"test email root: {'OK' if ok else 'FAIL'}")


if __name__ == "__main__":
    main()
