
import os
import smtplib
import webbrowser
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from livekit.agents import function_tool, RunContext
import pyautogui

# ==============================
# EMAIL
# ==============================
@function_tool()
async def send_email(context: RunContext, to_email: str, subject: str, message: str) -> str:
    user = os.getenv("GMAIL_USER")
    pwd = os.getenv("GMAIL_APP_PASSWORD")
    if not user or not pwd: return "Credentials missing"
    
    msg = MIMEMultipart()
    msg["From"], msg["To"], msg["Subject"] = user, to_email, subject
    msg.attach(MIMEText(message))
    
    try:
        with smtplib.SMTP("smtp.gmail.com", 587) as s:
            s.starttls()
            s.login(user, pwd)
            s.send_message(msg)
        return "Email sent"
    except Exception as e: return f"Error: {e}"

@function_tool()
async def get_email_count(context: RunContext, folder: str = "inbox") -> str:
    return "Email count (IMAP required)"

@function_tool()
async def get_recent_email_senders(context: RunContext, count: int = 5) -> str:
    return "Recent senders (IMAP required)"

@function_tool()
async def read_specific_email(context: RunContext, index: int = 1) -> str:
    return "Reading email... (IMAP required)"

@function_tool()
async def reply_to_latest_email(context: RunContext, reply_text: str) -> str:
    return "Replied (IMAP/SMTP required)"

@function_tool()
async def check_gmail_for_otp(context: RunContext) -> str:
    return "Checking OTP... (IMAP required)"

# ==============================
# WHATSAPP & PHONE
# ==============================
@function_tool()
async def send_whatsapp_message(context: RunContext, phone: str, message: str) -> str:
    webbrowser.open(f"https://web.whatsapp.com/send?phone={phone}&text={message}")
    time.sleep(15)
    pyautogui.press("enter")
    return "Message sent"

@function_tool()
async def send_whatsapp_image(context: RunContext, phone: str, image_path: str, message: str = "") -> str:
    return "Image sending via WhatsApp logic..."

@function_tool()
async def send_whatsapp_message_background(context: RunContext, phone: str, message: str) -> str:
    return await send_whatsapp_message(context, phone, message)

@function_tool()
async def make_phone_call(context: RunContext, phone_number: str) -> str:
    return f"Calling {phone_number} via ADB..."

@function_tool()
async def track_phone_number(context: RunContext, phone_number: str) -> str:
    try:
        import phonenumbers
        from phonenumbers import geocoder, carrier
        pn = phonenumbers.parse(phone_number)
        return f"Location: {geocoder.description_for_number(pn, 'en')} | Carrier: {carrier.name_for_number(pn, 'en')}"
    except: return "Tracking failed"

@function_tool()
async def get_latest_call_info(context: RunContext) -> str:
    return "Latest call info from ADB..."

@function_tool()
async def whatsapp_call(context: RunContext, phone: str, call_type: str = "voice") -> str:
    webbrowser.open(f"https://web.whatsapp.com/send?phone={phone}")
    return f"WhatsApp {call_type} call initiated"

@function_tool()
async def google_duo_call(context: RunContext, contact: str) -> str:
    webbrowser.open(f"https://duo.google.com/?contact_id={contact}")
    return "Duo call"

@function_tool()
async def start_google_meet(context: RunContext) -> str:
    webbrowser.open("https://meet.google.com/new")
    return "Meet started"

@function_tool()
async def universal_phone_unlocker(context: RunContext, wireless_addr: str = None, pairing_code: str = None) -> str:
    return "Unlocker sequence triggered (ADB)"

@function_tool()
async def common_phone_location_tracker(context: RunContext, phone_number: str) -> str:
     from tools.security import generate_phone_location_map # resolving circular dependency locally
     return await generate_phone_location_map(context, phone_number)
