import subprocess
import sys
import os
import smtplib
from email.message import EmailMessage
from dotenv import load_dotenv

# ───────────────────────────────────────────────
# 1. RUN PYTHON SCRIPTS (TRACK STATUS)
# ───────────────────────────────────────────────
scripts = [
    "search.py",
    "pdp.py",
    "best_seller.py"
]

script_map = {
    "search.py": "search",
    "pdp.py": "pdp",
    "best_seller.py": "best_seller"
}

script_status = {
    "search": False,
    "pdp": False,
    "best_seller": False
}

print("🚀 Starting automation...\n")

for script in scripts:
    print(f"▶ Running {script}...")
    result = subprocess.run(
        [sys.executable, script],
        capture_output=True,
        text=True
    )

    key = script_map[script]

    if result.returncode == 0:
        print(f"✅ {script} completed successfully")
        script_status[key] = True
    else:
        print(f"❌ Error in {script}")
        print(result.stderr)

print("\n📊 Script Execution Summary:", script_status)

# ───────────────────────────────────────────────
# 2. LOAD ENV VARIABLES
# ───────────────────────────────────────────────
load_dotenv()

SENDER_EMAIL = os.getenv("SENDER_EMAIL")
SENDER_PASSWORD = os.getenv("SENDER_PASSWORD")
SMTP_SERVER = os.getenv("SMTP_SERVER")
SMTP_PORT = int(os.getenv("SMTP_PORT"))

TO_EMAILS = [e.strip() for e in os.getenv("RECIPIENT_EMAILS").split(",")]
CC_EMAILS = [e.strip() for e in os.getenv("RECIPIENT_EMAILS_CC").split(",")]
BCC_EMAILS = [e.strip() for e in os.getenv("RECIPIENT_EMAILS_BCC").split(",")]

SERVER_DOMAIN = os.getenv("SERVER_DOMAIN")

ATTACHMENTS = [
    "uploaded_files/lg_prod_list2.xlsx",
    "uploaded_files/checkout_status.xlsx",
    "uploaded_files/updated_lg_prod_list.xlsx"
]

# ───────────────────────────────────────────────
# 3. BUTTON CONFIG LOGIC
# ───────────────────────────────────────────────
def button_config(success, path):
    if success:
        return f"{SERVER_DOMAIN}{path}", ""
    return "#", "pointer-events:none; opacity:0.5; background-color:#9ca3af;"

search_link, search_disabled = button_config(
    script_status["search"], "/uploaded_files/lg_prod_list2.xlsx"
)

pdp_link, pdp_disabled = button_config(
    script_status["pdp"], "/uploaded_files/checkout_status.xlsx"
)

best_link, best_disabled = button_config(
    script_status["best_seller"], "/uploaded_files/updated_lg_prod_list.xlsx"
)

# ───────────────────────────────────────────────
# 4. LOAD & UPDATE HTML TEMPLATE
# ───────────────────────────────────────────────
with open("email_template.html", "r") as f:
    html_content = f.read()

html_content = (
    html_content
    .replace("{{SEARCH_LINK}}", search_link)
    .replace("{{SEARCH_DISABLED_STYLE}}", search_disabled)
    .replace("{{PDP_LINK}}", pdp_link)
    .replace("{{PDP_DISABLED_STYLE}}", pdp_disabled)
    .replace("{{BEST_LINK}}", best_link)
    .replace("{{BEST_DISABLED_STYLE}}", best_disabled)
)

# ───────────────────────────────────────────────
# 5. CREATE EMAIL
# ───────────────────────────────────────────────
msg = EmailMessage()
msg["Subject"] = "Daily Checkout Reports – Search, PDP & Best Seller"
msg["From"] = SENDER_EMAIL
msg["To"] = ", ".join(TO_EMAILS)
msg["Cc"] = ", ".join(CC_EMAILS)

msg.set_content("Your email client does not support HTML.")
msg.add_alternative(html_content, subtype="html")

# ───────────────────────────────────────────────
# 6. ATTACH FILES (ONLY IF EXISTS)
# ───────────────────────────────────────────────
for file in ATTACHMENTS:
    if os.path.exists(file):
        with open(file, "rb") as f:
            msg.add_attachment(
                f.read(),
                maintype="application",
                subtype="vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                filename=os.path.basename(file)
            )

# ───────────────────────────────────────────────
# 7. SEND EMAIL (ALWAYS)
# ───────────────────────────────────────────────
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
    server.starttls()
    server.login(SENDER_EMAIL, SENDER_PASSWORD)
    server.send_message(
        msg,
        to_addrs=TO_EMAILS + CC_EMAILS + BCC_EMAILS
    )

print("\n📧 Email sent successfully.")
print("🎉 Automation completed.")