"""Review page: card-based classification UI for contacts with status 'Review'."""

from flask import Blueprint, render_template, request, g, session as flask_session

from webapp.auth import role_required
from icp_db import (
    get_review_contacts_with_suggestions,
    update_contact_status_by_id,
    get_contact_by_id,
)

review_bp = Blueprint("review", __name__)

# Cache the review queue in the session so we can track progress
# This is rebuilt on each page load of /review.


@review_bp.route("/review")
@role_required("editor")
def index():
    db = g.db
    contacts = get_review_contacts_with_suggestions(db)
    total = len(contacts)

    return render_template(
        "review.html",
        contacts=contacts,
        total=total,
    )


@review_bp.route("/review/<int:contact_id>/classify", methods=["POST"])
@role_required("editor")
def classify(contact_id):
    """Classify a contact and return the next review card via htmx."""
    db = g.db
    status = request.form.get("status")
    notes = request.form.get("notes", "").strip() or None
    company_override = request.form.get("company", "").strip() or None

    if status and status in ("ICP", "POI", "Not ICP"):
        # Update the contact status
        update_contact_status_by_id(db, contact_id, status, notes)

        # If company was overridden, update it too
        if company_override:
            from icp_db import Contact
            c = db.query(Contact).filter(Contact.id == contact_id).first()
            if c:
                c.company = company_override
                db.commit()

        # Learn from this classification
        contact = get_contact_by_id(db, contact_id)
        if contact:
            from icp_process import learn_from_classification
            learn_from_classification(
                contact["name"],
                contact["title"],
                company_override or contact["company"],
                status,
            )

        # Auto-sync to Zoho CRM when classified as ICP
        if status == "ICP":
            from webapp.zoho_helpers import trigger_zoho_sync
            trigger_zoho_sync(contact_id)

    # Get remaining review contacts for the next card
    remaining = get_review_contacts_with_suggestions(db)
    total_done = int(request.form.get("done_count", 0)) + (1 if status else 0)

    if not remaining:
        return render_template("partials/review_card.html", contact=None, done=total_done, total=total_done)

    return render_template(
        "partials/review_card.html",
        contact=remaining[0],
        remaining=len(remaining),
        done=total_done,
        total=total_done + len(remaining),
    )
