import frappe

@frappe.whitelist(allow_guest=True)  # allow_guest=True if you want unauthenticated access
def lead_magnet(email,subject,content):
    try:
        # Check if a Lead with the given email exists
        lead = frappe.db.get_value("Lead", {"email_id": email}, "name",)

        if not lead:
            # Create a new Lead if not found
            lead_doc = frappe.get_doc({
                "doctype": "Lead",
                "first_name": "Unknown",
                "email_id": email,
                "status": "Open"
            })
            lead_doc.insert(ignore_permissions=True)
            frappe.db.commit()
            lead = lead_doc.name  # Get the newly created lead name

        # Create a Communication linked to the Lead
        communication = frappe.get_doc({
            "doctype": "Communication",
            "subject": subject,
            "content": content,
            "sender": email,
            "sent_or_received": "Received",
            "reference_doctype": "Lead",
            "reference_name": lead  # Link to the existing or new lead
        })
        communication.insert(ignore_permissions=True)
        frappe.db.commit()

        return {"success": True, "message": "Lead and communication recorded successfully", "lead": lead}

    except Exception as e:
        frappe.log_error(f"Lead Creation Error: {str(e)}", "Lead API Error")
        return {"success": False, "error": str(e)}
