#!/usr/bin/env python3
"""
Nikita's Contact Form Backend
Receives form submissions and sends emails via Google Workspace CLI
"""

from flask import Flask, request, jsonify
from flask_cors import CORS
import subprocess
import json
from datetime import datetime
import os

app = Flask(__name__)
CORS(app)

NIKITA_EMAIL = "seonktzz@gmail.com"
GOG_ACCOUNT = "termosa.stanislav@gmail.com"

def send_email_via_gog(to_email, subject, body):
    """Send email using gog (Google Workspace CLI)"""
    try:
        # Write to temp file
        temp_file = "/tmp/email_body.txt"
        with open(temp_file, 'w', encoding='utf-8') as f:
            f.write(body)
        
        # Use gog to send email with --no-input to skip confirmations
        cmd = [
            '/root/bin/gog',
            'gmail',
            'send',
            f'--to={to_email}',
            f'--subject={subject}',
            f'--body-file={temp_file}',
            f'--account={GOG_ACCOUNT}',
            '--no-input',
            '--force'
        ]
        
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
        
        # Clean up
        try:
            os.remove(temp_file)
        except:
            pass
        
        if result.returncode == 0:
            return True, "Email sent successfully"
        else:
            # Log the error for debugging
            print(f"GOG Error: {result.stderr}")
            return False, result.stderr
            
    except subprocess.TimeoutExpired:
        return False, "Email send timed out"
    except Exception as e:
        print(f"Exception: {e}")
        return False, str(e)

@app.route('/api/contact', methods=['POST'])
def contact():
    """Handle contact form submission"""
    try:
        data = request.get_json()
        
        # Validate required fields
        name = data.get('name', '').strip()
        email = data.get('email', '').strip()
        message = data.get('message', '').strip()
        
        if not all([name, email, message]):
            return jsonify({'success': False, 'error': 'All fields are required'}), 400
        
        # Email to Nikita
        nikita_subject = f"New message from {name}"
        nikita_body = f"""
Hi Nikita,

You have a new message from your contact form:

From: {name}
Email: {email}
Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

Message:
{message}

---
Reply to: {email}
"""
        
        success, msg = send_email_via_gog(NIKITA_EMAIL, nikita_subject, nikita_body)
        
        if not success:
            return jsonify({'success': False, 'error': 'Failed to send email to Nikita'}), 500
        
        # Confirmation email to sender
        sender_subject = "We received your message"
        sender_body = f"""
Hi {name},

Thanks for reaching out! We received your message and Nikita will get back to you as soon as possible.

Your message:
{message}

---
Nikita | Marketing Expert
"""
        
        send_email_via_gog(email, sender_subject, sender_body)
        
        return jsonify({
            'success': True,
            'message': 'Message sent successfully! Check your email for confirmation.'
        }), 200
        
    except Exception as e:
        print(f"Error: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/health', methods=['GET'])
def health():
    """Health check endpoint"""
    return jsonify({'status': 'ok'}), 200

if __name__ == '__main__':
    # Run on localhost:8012
    app.run(host='127.0.0.1', port=8012, debug=False)
