import imaplib
import email
import re
from bs4 import BeautifulSoup
from django.conf import settings
from crm.models import Lead, LeadContact


def sync_leads():
    mail = imaplib.IMAP4_SSL(settings.EMAIL_IMAP_HOST)
    mail.login(settings.EMAIL_IMAP_USER, settings.EMAIL_IMAP_PASS)
    mail.select("inbox")

    status, messages = mail.search(None, f'(UNSEEN SUBJECT "{settings.EMAIL_SUBJECT_FILTER}")')
    email_ids = messages[0].split()
    print(f"Found {len(email_ids)} emails")

    for e_id in email_ids:
        _, msg_data = mail.fetch(e_id, "(RFC822)")

        for response_part in msg_data:
            if not isinstance(response_part, tuple):
                continue

            msg = email.message_from_bytes(response_part[1])
            body = ""

            if msg.is_multipart():
                for part in msg.walk():
                    content_type = part.get_content_type()
                    if content_type == "text/plain":
                        body = part.get_payload(decode=True).decode()
                    elif content_type == "text/html":
                        html = part.get_payload(decode=True).decode()
                        body = BeautifulSoup(html, "html.parser").get_text()
            else:
                body = msg.get_payload(decode=True).decode()

            company_name = extract_field(body, "Company Name") or ""
            enquiry_from = extract_field(body, "Enquiry From") or ""
            mobile = extract_field(body, "Mobile") or ""
            email_id = extract_field(body, "Email") or ""
            service = extract_field(body, "service") or ""

            if LeadContact.objects.filter(email=email_id, lead__company_name=company_name).exists():
                print(f"Skipped duplicate: {company_name}")
                continue

            lead = Lead.objects.create(
                company_name=company_name,
                source="google",
                service=service,
            )
            LeadContact.objects.create(
                lead=lead,
                name=enquiry_from,
                phone=mobile,
                email=email_id,
            )
            print(f"Lead created: {company_name}")

    mail.logout()


def extract_field(body, field_name):
    match = re.search(rf"{field_name}\s*:\s*(.*)", body, re.IGNORECASE)
    return match.group(1).strip() if match else None
