import frappe
from werkzeug.wrappers import Response


@frappe.whitelist(allow_guest=True)
def update_response(name, response):
    """Update the response for a given estimate."""
    print("DEBUG: RESPONSE RECEIVED:", name, response)
    try:
        if not frappe.db.exists("Quotation", name):
            raise Exception("Estimate not found.")
        estimate = frappe.get_doc("Quotation", name)
        if estimate.docstatus != 1:
            raise Exception("Estimate must be submitted to update response.")
        accepted = True if response == "Accepted" else False
        new_status = "Estimate Accepted" if accepted else "Lost"

        estimate.custom_response = response
        estimate.custom_current_status = new_status
        estimate.custom_followup_needed = 1 if response == "Requested call" else 0
        # estimate.status = "Ordered" if accepted else "Closed"
        estimate.flags.ignore_permissions = True
        print("DEBUG: Updating estimate with response:", response, "and status:", new_status)
        estimate.save()

        if accepted:
            template = "custom_ui/templates/estimates/accepted.html"
            # if check_if_customer(estimate.party_name):
            #     print("DEBUG: Party is already a customer:", estimate.party_name)
            # else:
            #     print("DEBUG: Converting lead to customer for party:", estimate.party_name)
            #     convert_lead_to_customer(estimate.party_name)
        elif response == "Requested call":
            template = "custom_ui/templates/estimates/request-call.html"
        else:
            template = "custom_ui/templates/estimates/rejected.html"
        html = frappe.render_template(template, {"doc": estimate})
        frappe.db.commit()
        return Response(html, mimetype="text/html")
    except Exception as e:
        template = "custom_ui/templates/estimates/error.html"
        html = frappe.render_template(template, {"error": str(e)})
        return Response(html, mimetype="text/html")