#!/usr/bin/env python3
"""
Prepare Outreach Emails based on Website Audits.
Generates personalized email drafts for tradies using audit data.
"""

import os
import sys
import json
from pathlib import Path

# Add scripts dir to path to import browser_agent (for API key config only)
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from browser_agent import BrowserAgent

try:
    import google.generativeai as genai
except ImportError:
    print("ERROR: google-generativeai not installed.")
    sys.exit(1)

AUDIT_DIR = Path("/mnt/e/genesis-system/data/AUDITS")
MODEL_NAME = "gemini-3-pro-preview"

# Configure API Key (reusing logic from BrowserAgent)
api_key = os.environ.get("GOOGLE_API_KEY")
if not api_key:
    key_path = Path("/mnt/e/genesis-system/Credentials/gemini_api_key.txt")
    if key_path.exists():
        api_key = key_path.read_text().strip()
        os.environ["GOOGLE_API_KEY"] = api_key

if api_key:
    genai.configure(api_key=api_key)
else:
    print("ERROR: GOOGLE_API_KEY not found.")
    sys.exit(1)

def generate_email(company_name, audit_content, lead_data):
    """Generate personalized email draft."""
    
    first_name = lead_data.get("First Name") or "there"
    
    prompt = f"""
    You are Kinan, founder of Sunaiva. You help tradies get more leads.
    Write a short, high-impact cold email to '{first_name}' at '{company_name}'.
    
    **Context:**
    We just audited their website and found specific issues.
    Use the audit findings below to personalize the email.
    
    **Audit Findings:**
    {audit_content[:2000]} (truncated)
    
    **Goal:**
    Get them to book a 15-min call to see how a Voice AI agent can fix their missed calls.
    
    **Requirements:**
    1. Subject line: Short, punchy (e.g., "Missed calls at {company_name}?", "Your website audit").
    2. Opening: "I was looking for a plumber in [City] and found your site..."
    3. The Hook: Mention 1 specific thing from the audit (e.g., "I noticed you don't have a booking form").
    4. The Value: "We built an AI receptionist that answers calls 24/7. It would fix this instantly."
    5. CTA: "Open to a 15-min demo?"
    6. Sign off: Kinan.
    
    Keep it under 150 words. No fluff. Australian tone.
    """
    
    try:
        model = genai.GenerativeModel(MODEL_NAME)
        response = model.generate_content(prompt)
        return response.text
    except Exception as e:
        return f"Error generating email: {e}"

def main():
    print(f"Generating outreach emails from {AUDIT_DIR}...")
    
    count = 0
    for company_dir in AUDIT_DIR.iterdir():
        if not company_dir.is_dir():
            continue
            
        audit_file = company_dir / "audit.md"
        lead_file = company_dir / "lead_data.json"
        
        if audit_file.exists() and lead_file.exists():
            print(f"Processing {company_dir.name}...")
            
            audit_content = audit_file.read_text()
            lead_data = json.loads(lead_file.read_text())
            
            email_draft = generate_email(lead_data.get("Company"), audit_content, lead_data)
            
            (company_dir / "email_draft.txt").write_text(email_draft)
            print(f"  Draft saved to {company_dir}/email_draft.txt")
            count += 1
            
    print(f"Done. Generated {count} email drafts.")

if __name__ == "__main__":
    main()
