import os
from datetime import datetime, date
from imap_tools import MailBox, AND
import mysql.connector
from dotenv import load_dotenv
from db_utils import get_db, save_message
from bs4 import BeautifulSoup

load_dotenv()

EMAIL_DATE_FROM = os.getenv("EMAIL_FETCH_DATE_FROM")
EMAIL_FETCH_LIMIT = int(os.getenv("EMAIL_FETCH_LIMIT", 100))

if EMAIL_DATE_FROM:
    DATE_FROM = datetime.strptime(EMAIL_DATE_FROM, "%Y-%m-%d").date()
else:
    DATE_FROM = date.today()

def get_message_content(msg):
    if msg.text:
        return msg.text
    elif msg.html:
        return BeautifulSoup(msg.html, "html.parser").get_text()
    return ""


def save_message_if_new(db, user_id, name, identifier, source, direction, content, timestamp, channel, subject):
    cursor = db.cursor()

    if "@" in identifier:
        email = identifier
        phone = None
        name = name or identifier.split("@")[0].replace(".", " ").title()
    else:
        email = None
        phone = identifier
        name = name or identifier

    cursor.execute("SELECT id FROM contact WHERE (email = %s OR phone = %s) AND source = %s", (email, phone, source))
    row = cursor.fetchone()
    if row:
        contact_id = row[0]
    else:
        cursor.execute("INSERT INTO contact (name, email, phone, source) VALUES (%s, %s, %s, %s)", (name, email, phone, source))
        db.commit()
        contact_id = cursor.lastrowid

    cursor.execute("SELECT id FROM message WHERE contact_id = %s AND timestamp = %s AND subject = %s", (contact_id, timestamp, subject))
    if cursor.fetchone():
        print(f"⚠️ Mensaje duplicado @ {timestamp}")
        return

    cursor.execute("""
        INSERT INTO message (user_id, contact_id, direction, content, timestamp, channel, subject)
        VALUES (%s, %s, %s, %s, %s, %s, %s)
    """, (user_id, contact_id, direction, content, timestamp, channel, subject))
    db.commit()






def importar_emails_de_usuario(usuario):
    db = get_db()
    email = usuario['email']
    password = usuario['email_password']
    print(f"📧 Conectando con {email}")

    try:
        print("📧 Descargando inbox")
        with MailBox('imap.gmail.com').login(email, password) as mailbox:
            for msg in mailbox.fetch(AND(date_gte=DATE_FROM), limit=EMAIL_FETCH_LIMIT):
                print(f"  📧 Mensaje de {msg.from_} a {msg.to}")
                save_message_if_new(db, usuario['id'], msg.from_, msg.from_, 'email', 'incoming', get_message_content(msg), msg.date, 'email', msg.subject)

        print("📧 Descargando enviados")
        with MailBox('imap.gmail.com').login(email, password, initial_folder='[Gmail]/Enviados') as mailbox:
            for msg in mailbox.fetch(limit=EMAIL_FETCH_LIMIT):
                save_message_if_new(db, usuario['id'], msg.to[0], msg.to[0], 'email', 'outgoing', get_message_content(msg), msg.date, 'email', msg.subject)

        print(f"✅ Emails importados de {email}")
    except Exception as e:
        print(f"❌ Error con {email}: {e}")

def main():
    db = get_db()
    cursor = db.cursor(dictionary=True)
    cursor.execute("SELECT * FROM user_account WHERE email IS NOT NULL AND email_password IS NOT NULL and status = 'enabled'")
    usuarios = cursor.fetchall()
    for usuario in usuarios:
        importar_emails_de_usuario(usuario)

if __name__ == '__main__':
    main()
