import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

from fastapi import APIRouter, HTTPException, BackgroundTasks
from pydantic import BaseModel

try:
    import boto3
    HAS_BOTO3 = True
except ImportError:
    HAS_BOTO3 = False

router = APIRouter(prefix="/api/investors", tags=["investors"])

class InvestorContact(BaseModel):
    email: str

def send_investor_email(investor_email: str):
    # AWS SES Configuration
    aws_region = os.getenv("AWS_REGION", "eu-west-1")
    aws_access_key = os.getenv("AWS_ACCESS_KEY_ID")
    aws_secret_key = os.getenv("AWS_SECRET_ACCESS_KEY")
    target_email = os.getenv("AWS_SES_RECEIVER_EMAIL", "office@wavegroup.ai")
    aws_sender = os.getenv("AWS_SES_SENDER_EMAIL", target_email)
    
    # Try AWS SES first if credentials are provided
    if HAS_BOTO3 and aws_access_key and aws_secret_key:
        try:
            ses = boto3.client(
                'ses',
                region_name=aws_region,
                aws_access_key_id=aws_access_key,
                aws_secret_access_key=aws_secret_key
            )
            
            response = ses.send_email(
                Source=aws_sender,
                Destination={'ToAddresses': [target_email]},
                Message={
                    'Subject': {'Data': f"New Investor Interest: {investor_email}"},
                    'Body': {
                        'Text': {'Data': f"A new potential investor has expressed interest in ACI Platform.\n\nInvestor Email: {investor_email}"}
                    }
                }
            )
            print(f"Successfully sent SES email: {response['MessageId']}")
            return
        except Exception as e:
            print(f"AWS SES failed, trying SMTP fallback... Error: {e}")

    # SMTP Fallback
    smtp_host = os.getenv("SMTP_HOST")
    smtp_port = os.getenv("SMTP_PORT")
    smtp_user = os.getenv("SMTP_USER")
    smtp_pass = os.getenv("SMTP_PASSWORD")

    if not all([smtp_host, smtp_port, smtp_user, smtp_pass]):
        print(f"Warning: No valid email service configured. Lead from: {investor_email}")
        return

    msg = MIMEMultipart()
    msg['From'] = smtp_user
    msg['To'] = target_email
    msg['Subject'] = f"New Investor Interest: {investor_email}"
    msg.attach(MIMEText(f"Investor Email: {investor_email}", 'plain'))

    try:
        with smtplib.SMTP(smtp_host, int(smtp_port)) as server:
            server.starttls()
            server.login(smtp_user, smtp_pass)
            server.send_message(msg)
    except Exception as e:
        print(f"Error sending SMTP email: {e}")

@router.post("/interest")
async def register_interest(contact: InvestorContact, background_tasks: BackgroundTasks):
    background_tasks.add_task(send_investor_email, contact.email)
    return {"message": "Interest registered successfully"}
