import os
import random
import time
import base64
from pathlib import Path
from dotenv import load_dotenv

from app.db.db import get_col
from app.utility.email import send_email

load_dotenv()

OTP_EXP_SECONDS = int(os.getenv("OTP_EXP_SECONDS", 600))
EMAIL_STRICT = os.getenv("EMAIL_STRICT", "false").lower() in {"1", "true", "yes", "on"}

def load_logo_base64():
    # Try multiple possible paths for the logo
    possible_paths = [
        Path("app/logo/NbitzLogo.png"),
        Path(__file__).parent.parent / "logo" / "NbitzLogo.png",
        Path(__file__).parent.parent.parent / "app" / "logo" / "NbitzLogo.png",
    ]
    
    for logo_path in possible_paths:
        if logo_path.exists():
            with open(logo_path, "rb") as image_file:
                return base64.b64encode(image_file.read()).decode("utf-8")
    
    # Return empty string if logo not found (email will still work)
    return ""


def generate_numeric_otp(length: int = 6) -> str:
    if length < 4:
        length = 4
    return "".join(str(random.randint(0, 9)) for _ in range(length))


def create_email_otp(email: str, purpose: str) -> str:
    """
    purpose: e.g. "verify_email" or "reset_password"
    """
    col = get_col("otps")
    otp = generate_numeric_otp()
    now = int(time.time())
    col.update_one(
        {"email": email.lower(), "purpose": purpose},
        {"$set": {"email": email.lower(), "purpose": purpose, "otp": otp, "createdAt": now, "expiresAt": now + OTP_EXP_SECONDS}},
        upsert=True,
    )
    return otp


def verify_email_otp(email: str, purpose: str, otp: str) -> bool:
    col = get_col("otps")
    rec = col.find_one({"email": email.lower(), "purpose": purpose})
    if not rec:
        return False
    now = int(time.time())
    if now > int(rec.get("expiresAt", 0)):
        return False
    if str(rec.get("otp")) != str(otp):
        return False
    col.delete_one({"_id": rec["_id"]})
    return True


def send_otp_via_email(email: str, otp: str, purpose: str) -> None:
    logo_base64 = load_logo_base64()

    subject = "Your OTP Code"
    text = f"Your OTP for {purpose.replace('_', ' ')} is: {otp}\nThis code will expire in {OTP_EXP_SECONDS//60} minutes."

    # Build HTML with logo if available
    logo_html = ""
    if logo_base64:
        logo_html = f'<img src="data:image/png;base64,{logo_base64}" alt="Nbitz Logo" style="width:150px;margin-bottom:20px;" />'
    
    html = f"""
    <div style="font-family:Arial,sans-serif;line-height:1.5;">
      {logo_html}
      <h2>OTP for {purpose.replace('_', ' ').title()}</h2>
      <p>Your one-time code is:</p>
      <p style="font-size:22px;font-weight:700;letter-spacing:3px;">{otp}</p>
      <p>This code expires in {OTP_EXP_SECONDS//60} minutes.</p>
      <p>If you didn't request this, you can ignore this email.</p>
    </div>
    """

    try:
        send_email(subject, [email], html=html, text=text)
    except Exception as exc:
        # Fall back to console logging so flows are still testable in dev
        print(f"[EMAIL OTP FAILED] {exc}")
        print(f"[EMAIL OTP] To: {email} | Purpose: {purpose} | OTP: {otp}")
        if EMAIL_STRICT:
            raise


