#!/usr/bin/env python3
"""Send approval email to Kinan when ReceptionistAI is demo-ready."""
import os
import sys
import json
import urllib.request
import urllib.error
from datetime import datetime
from typing import Dict, List, Optional

# Email configuration
RESEND_API_KEY = os.getenv('RESEND_API_KEY', '')
KINAN_EMAILS = {
    'primary': 'kinan@protonmail.com',
    'work': 'kinan@agileadapt.com'
}
EMAIL_FROM = 'genesis@sunaivadigital.com'
EMAIL_FROM_DISPLAY = 'Genesis Command Centre'


def send_via_resend(to_email: str, subject: str, html_body: str) -> Dict:
    """Send email via Resend API."""
    if not RESEND_API_KEY:
        return {
            "error": "RESEND_API_KEY not set",
            "status": "skipped",
            "reason": "API key missing. Set RESEND_API_KEY environment variable"
        }
    
    payload = {
        "from": f"{EMAIL_FROM_DISPLAY} <{EMAIL_FROM}>",
        "to": [to_email],
        "subject": subject,
        "html": html_body
    }
    
    data = json.dumps(payload).encode('utf-8')
    
    req = urllib.request.Request(
        "https://api.resend.com/emails",
        data=data,
        headers={
            "Authorization": f"Bearer {RESEND_API_KEY}",
            "Content-Type": "application/json"
        },
        method="POST"
    )
    
    try:
        with urllib.request.urlopen(req, timeout=10) as response:
            response_data = json.loads(response.read().decode('utf-8'))
            return {
                "status": "sent",
                "to": to_email,
                "id": response_data.get('id'),
                "timestamp": datetime.now().isoformat()
            }
    except urllib.error.HTTPError as e:
        error_body = e.read().decode('utf-8')
        return {
            "error": f"HTTP {e.code}",
            "status": "failed",
            "message": error_body
        }
    except Exception as e:
        return {
            "error": str(e),
            "status": "failed",
            "message": "Network or parsing error"
        }


def build_approval_email(items_completed: List[str], demo_url: str = None) -> tuple:
    """Build approval email subject and HTML body."""
    subject = "🚀 ReceptionistAI READY FOR APPROVAL — George Demo Feb 20"
    
    demo_url = demo_url or "https://api.sunaivadigital.com/demo/bunker/"
    
    items_html = ''.join(f'<li>{item}</li>' for item in items_completed)
    
    body = f"""<!DOCTYPE html>
<html>
<head>
    <style>
        body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif; line-height: 1.6; color: #333; }}
        .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
        .header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 8px 8px 0 0; }}
        .content {{ background: #f9f9f9; padding: 20px; border-radius: 0 0 8px 8px; }}
        .section {{ margin-bottom: 20px; }}
        .section h3 {{ color: #667eea; margin-top: 0; }}
        .section ol, .section ul {{ margin-left: 20px; }}
        .cta {{ display: inline-block; background: #667eea; color: white; padding: 10px 20px; border-radius: 5px; text-decoration: none; margin-top: 10px; }}
        .timestamp {{ color: #999; font-size: 12px; }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2 style="margin: 0;">Genesis Command Centre — Approval Required</h2>
        </div>
        <div class="content">
            <p class="timestamp"><strong>Timestamp:</strong> {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}</p>
            
            <div class="section">
                <h3>Completed This Session:</h3>
                <ul>
                    {items_html}
                </ul>
            </div>
            
            <div class="section">
                <h3>Demo URL:</h3>
                <p><a href="{demo_url}" class="cta">Visit Demo →</a></p>
                <p><code>{demo_url}</code></p>
            </div>
            
            <div class="section">
                <h3>Your Approval Actions:</h3>
                <ol>
                    <li><strong>Test as User Zero</strong> — Visit demo URL, complete full journey</li>
                    <li><strong>GHL Setup</strong> — Settings → Team Members → Add yourself</li>
                    <li><strong>Activate Workflows</strong> — Automation → Activate 38 draft automations</li>
                    <li><strong>Approve Launch</strong> — Reply "APPROVED" to launch Instantly outreach</li>
                </ol>
            </div>
            
            <div class="section" style="border-top: 1px solid #ddd; padding-top: 15px; color: #666; font-size: 14px;">
                <p><em>Genesis has handled all technical setup autonomously. Your approval triggers customer acquisition.</em></p>
            </div>
        </div>
    </div>
</body>
</html>"""
    
    return subject, body


def notify_approval_ready(items_completed: List[str] = None, 
                         target_email: str = None,
                         demo_url: str = None,
                         dry_run: bool = False) -> Dict:
    """
    Send approval notification email to Kinan.
    
    Args:
        items_completed: List of completed work items
        target_email: Override target email (default: kinan@protonmail.com)
        demo_url: Override demo URL
        dry_run: If True, print email without sending
    
    Returns:
        Dictionary with send status
    """
    if items_completed is None:
        items_completed = [
            "ReceptionistAI audit complete",
            "Demo site deployed and tested",
            "GHL automation workflows configured",
            "Telnyx voice agent active (+61 7 3130 4377)",
            "Email notifications ready"
        ]
    
    target_email = target_email or KINAN_EMAILS['primary']
    subject, body = build_approval_email(items_completed, demo_url)
    
    if dry_run:
        print(f"\n{'='*60}")
        print(f"DRY RUN — Email not sent")
        print(f"{'='*60}")
        print(f"To: {target_email}")
        print(f"From: {EMAIL_FROM_DISPLAY} <{EMAIL_FROM}>")
        print(f"Subject: {subject}")
        print(f"\n{body}\n")
        return {"status": "dry_run", "to": target_email}
    
    print(f"\nSending approval notification to {target_email}...")
    result = send_via_resend(target_email, subject, body)
    
    if result.get("status") == "sent":
        print(f"✓ Email sent successfully (ID: {result.get('id')})")
    else:
        print(f"✗ Email failed: {result.get('error')}")
        print(f"  Reason: {result.get('message', 'Unknown')}")
    
    return result


if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="Send Kinan approval notification")
    parser.add_argument('--dry-run', action='store_true', help="Print email without sending")
    parser.add_argument('--work', nargs='+', help="List of completed work items")
    parser.add_argument('--email', default=None, help="Override target email")
    parser.add_argument('--demo-url', default=None, help="Override demo URL")
    parser.add_argument('--show-status', action='store_true', help="Show API key and config status")
    
    args = parser.parse_args()
    
    if args.show_status:
        print(f"\n{'='*60}")
        print("APPROVAL NOTIFICATION SYSTEM STATUS")
        print(f"{'='*60}")
        print(f"RESEND API Key: {'SET' if RESEND_API_KEY else 'NOT SET (required to send)'}")
        print(f"Primary Email: {KINAN_EMAILS['primary']}")
        print(f"Work Email: {KINAN_EMAILS['work']}")
        print(f"From Address: {EMAIL_FROM}")
        print(f"{'='*60}\n")
        sys.exit(0)
    
    result = notify_approval_ready(
        items_completed=args.work,
        target_email=args.email,
        demo_url=args.demo_url,
        dry_run=args.dry_run
    )
    
    # Exit with error code if send failed
    sys.exit(0 if result.get("status") in ["sent", "dry_run"] else 1)
