
import os
import shutil
import subprocess
from livekit.agents import function_tool, RunContext

# ==============================
# PRODUCTIVITY (FOCUS MODE)
# ==============================

HOSTS_PATH = r"C:\Windows\System32\drivers\etc\hosts"
BACKUP_PATH = r"C:\Windows\System32\drivers\etc\hosts.bak"

@function_tool()
async def enable_focus_mode(context: RunContext, websites: list[str]) -> str:
    """
    Blocks the specified websites by modifying the hosts file.
    Requires Administrator privileges.
    """
    try:
        # Backup hosts file if not exists
        if not os.path.exists(BACKUP_PATH):
            shutil.copy(HOSTS_PATH, BACKUP_PATH)

        with open(HOSTS_PATH, "r") as f:
            content = f.read()

        new_entries = "\n# FOCUS MODE START\n"
        for site in websites:
            # Clean domain
            domain = site.replace("https://", "").replace("http://", "").replace("www.", "").strip()
            if domain not in content:
                new_entries += f"127.0.0.1 {domain}\n"
                new_entries += f"127.0.0.1 www.{domain}\n"
        new_entries += "# FOCUS MODE END\n"

        with open(HOSTS_PATH, "a") as f:
            f.write(new_entries)

        # Flush DNS
        subprocess.run("ipconfig /flushdns", shell=True)
        return f"✅ Focus Mode ENABLED. Blocked: {', '.join(websites)}"

    except PermissionError:
        return "❌ Permission Denied: Run Friday as Administrator."
    except Exception as e:
        return f"❌ Failed to enable Focus Mode: {e}"

@function_tool()
async def disable_focus_mode(context: RunContext) -> str:
    """
    Restores the original hosts file to unblock websites.
    """
    try:
        if os.path.exists(BACKUP_PATH):
            shutil.copy(BACKUP_PATH, HOSTS_PATH)
            subprocess.run("ipconfig /flushdns", shell=True)
            return "✅ Focus Mode DISABLED. Websites unblocked."
        else:
            return "❌ No backup found. Cannot restore hosts file."
    except PermissionError:
        return "❌ Permission Denied: Run Friday as Administrator."
    except Exception as e:
        return f"❌ Failed to disable Focus Mode: {e}"

@function_tool()
async def add_smart_reminder(context: RunContext, task: str, time_at: str) -> str:
    import json
    reminder_file = "reminders.json"
    reminders = []
    if os.path.exists(reminder_file):
        with open(reminder_file, "r") as f:
            reminders = json.load(f)
    
    reminders.append({
        "task": task,
        "time": time_at,
        "notified": False,
        "date": "2026-02-06" # placeholder
    })
    
    with open(reminder_file, "w") as f:
        json.dump(reminders, f, indent=2)
        
    return f"Reminder set for {task} at {time_at}"

async def check_and_notify_reminders(session):
    if not session:
        return

    import json
    from datetime import datetime
    reminder_file = "reminders.json"
    
    if not os.path.exists(reminder_file):
        return

    with open(reminder_file, "r") as f:
        reminders = json.load(f)

    now = datetime.now()
    current_time = now.strftime("%H:%M")
    current_date = now.strftime("%Y-%m-%d")
    
    changed = False
    for r in reminders:
        if not r.get("notified") and (r.get("date") == current_date or r.get("date") == "2026-02-06") and r.get("time") == current_time:
            # Notify
            print(f"🔔 NOTIFICATION: {r['task']}")
            try:
                await session.generate_reply(instructions=f"PROACTIVE REMINDER: Tell the user it's time for: {r['task']}")
                r["notified"] = True
                changed = True
            except Exception as e:
                print(f"Failed to send notification: {e}")

    if changed:
        with open(reminder_file, "w") as f:
            json.dump(reminders, f, indent=2)

