import http.server
import socketserver
import json
import os
import time
import sys
import urllib.parse
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from urllib.parse import urlparse

# --- PROFESSIONAL CONFIGURATION ---
PORT = int(os.environ.get('PORT', 5000))
BACKEND_DIR = os.path.dirname(os.path.abspath(__file__))
WEBSITE_DIR = os.path.abspath(os.path.join(BACKEND_DIR, '..'))
UPLOADS_DIR = os.path.join(BACKEND_DIR, 'uploads')
DB_FILE = os.path.join(BACKEND_DIR, 'gallery.json')
INQUIRIES_FILE = os.path.join(BACKEND_DIR, 'inquiries.json')

# --- EMAIL CONFIGURATION (OPTIONAL) ---
# To enable email sending, create a file named 'email_config.json' in the backend folder
# with your Gmail address and an App Password.
EMAIL_CONFIG_FILE = os.path.join(BACKEND_DIR, 'email_config.json')

def send_email_notification(inquiry_data):
    """Sends an email notification if config exists."""
    if not os.path.exists(EMAIL_CONFIG_FILE):
        return False
    
    try:
        with open(EMAIL_CONFIG_FILE, 'r') as f:
            config = json.load(f)
            
        sender_email = config.get('email')
        app_password = config.get('app_password')
        receiver_email = config.get('receiver', 'enquries@udecltd.com')
        
        if not sender_email or not app_password:
            return False

        # Create message
        msg = MIMEMultipart()
        msg['From'] = sender_email
        msg['To'] = receiver_email
        msg['Subject'] = f"New Inquiry: {inquiry_data.get('Fullname', 'No Name')}"
        
        body = f"""
        New Inquiry Received!
        
        Full Name: {inquiry_data.get('Fullname')}
        Email: {inquiry_data.get('_replyto')}
        Message: {inquiry_data.get('Message')}
        
        Timestamp: {inquiry_data.get('timestamp')}
        """
        msg.attach(MIMEText(body, 'plain'))

        # Send using Gmail SMTP
        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
            server.login(sender_email, app_password)
            server.send_message(msg)
            
        print(f"[*] Email notification sent to {receiver_email}")
        return True
    except Exception as e:
        print(f"[!] Email Send Error: {e}")
        return False

# Ensure directories exist
for d in [UPLOADS_DIR]:
    if not os.path.exists(d):
        os.makedirs(d, exist_ok=True)

def init_db():
    """Initialize the database with existing images if it doesn't exist."""
    if not os.path.exists(DB_FILE) or os.path.getsize(DB_FILE) == 0:
        initial_data = []
        if os.path.exists(WEBSITE_DIR):
            for filename in os.listdir(WEBSITE_DIR):
                if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')):
                    # Only pick relevant project images
                    if any(word in filename.lower() for word in ['project', 'bespoke', 'marble', 'island', 'background']):
                        initial_data.append({
                            "id": int(time.time() * 1000) + len(initial_data),
                            "title": filename.split('.')[0].replace('-', ' ').replace('_', ' ').title(),
                            "imageUrl": f"/initial/{filename}",
                            "filename": filename,
                            "isInitial": True
                        })
        with open(DB_FILE, 'w') as f:
            json.dump(initial_data, f, indent=4)
        print(f"[*] Database initialized with {len(initial_data)} images.")

class GalleryHandler(http.server.BaseHTTPRequestHandler):
    """Custom handler to manage Gallery API and Image serving."""
    
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        super().end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

    def do_GET(self):
        parsed_path = urlparse(self.path)
        path = parsed_path.path

        # 1. API: Get Gallery
        if path == '/api/gallery':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            
            data = []
            if os.path.exists(DB_FILE):
                try:
                    with open(DB_FILE, 'r') as f:
                        data = json.load(f)
                    
                    # Fix URLs to be absolute for the current requester
                    host = self.headers.get('Host', f'localhost:{PORT}')
                    protocol = 'https' if self.headers.get('X-Forwarded-Proto') == 'https' else 'http'
                    for item in data:
                        prefix = '/initial/' if item.get('isInitial') else '/uploads/'
                        item['imageUrl'] = f"{protocol}://{host}{prefix}{urllib.parse.quote(item['filename'])}"
                except Exception as e:
                    print(f"[!] DB Load Error: {e}")
            
            self.wfile.write(json.dumps(data).encode('utf-8'))

        # 2. Serve Initial Images
        elif path.startswith('/initial/'):
            filename = urllib.parse.unquote(path.replace('/initial/', ''))
            file_path = os.path.join(WEBSITE_DIR, filename)
            self.serve_static_file(file_path)

        # 3. Serve Uploaded Images
        elif path.startswith('/uploads/'):
            filename = urllib.parse.unquote(path.replace('/uploads/', ''))
            file_path = os.path.join(UPLOADS_DIR, filename)
            self.serve_static_file(file_path)
            
        # 4. Serve Admin Page (New)
        elif path == '/admin' or path == '/admin.html':
            file_path = os.path.join(BACKEND_DIR, 'admin.html')
            self.serve_static_file(file_path)
            
        else:
            self.send_error(404, "Not Found")

    def serve_static_file(self, file_path):
        if os.path.exists(file_path) and os.path.isfile(file_path):
            self.send_response(200)
            ext = file_path.lower().split('.')[-1]
            content_types = {
                'jpg': 'image/jpeg', 'jpeg': 'image/jpeg',
                'png': 'image/png', 'webp': 'image/webp',
                'html': 'text/html', 'css': 'text/css', 'js': 'application/javascript'
            }
            self.send_header('Content-Type', content_types.get(ext, 'application/octet-stream'))
            self.send_header('Cache-Control', 'public, max-age=86400')
            self.end_headers()
            with open(file_path, 'rb') as f:
                self.wfile.write(f.read())
        else:
            self.send_error(404, "File Not Found")

    def do_POST(self):
        parsed_path = urlparse(self.path)
        path = parsed_path.path

        # 1. API: Contact Form Handling
        if path == '/api/contact':
            try:
                content_length = int(self.headers.get('Content-Length', 0))
                body = self.rfile.read(content_length)
                data = json.loads(body.decode('utf-8'))
                
                # Add timestamp
                data['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
                
                # Save locally to inquiries.json (Backup)
                inquiries = []
                if os.path.exists(INQUIRIES_FILE):
                    with open(INQUIRIES_FILE, 'r') as f:
                        inquiries = json.load(f)
                
                inquiries.append(data)
                with open(INQUIRIES_FILE, 'w') as f:
                    json.dump(inquiries, f, indent=4)
                
                print(f"[*] New Inquiry Received from: {data.get('Fullname')}")
                
                # Attempt to send email (if config exists)
                send_email_notification(data)
                
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"success": True, "message": "Inquiry received"}).encode('utf-8'))
                return
            except Exception as e:
                print(f"[!] Contact Error: {e}")
                self.send_error(500, str(e))
                return

        # 2. API: Gallery Upload Handling
        if path == '/api/gallery':
            ctype = self.headers.get('Content-Type', '')
            if 'multipart/form-data' not in ctype:
                self.send_error(400, "Bad Request: Expected multipart/form-data")
                return

            try:
                # Basic multipart parsing (since we have no external libs)
                boundary = ctype.split("boundary=")[1].encode()
                content_length = int(self.headers.get('Content-Length', 0))
                body = self.rfile.read(content_length)

                parts = body.split(b'--' + boundary)
                title = "New Project"
                image_data = None
                filename = "upload.jpg"

                for part in parts:
                    if b'name="title"' in part:
                        title = part.split(b'\r\n\r\n')[1].split(b'\r\n')[0].decode('utf-8')
                    elif b'name="image"' in part:
                        if b'filename="' in part:
                            filename = part.split(b'filename="')[1].split(b'"')[0].decode('utf-8')
                        image_data = part.split(b'\r\n\r\n')[1].rsplit(b'\r\n', 1)[0]

                if image_data:
                    safe_filename = f"{int(time.time())}_{filename.replace(' ', '_')}"
                    save_path = os.path.join(UPLOADS_DIR, safe_filename)
                    
                    with open(save_path, 'wb') as f:
                        f.write(image_data)
                    
                    new_item = {
                        "id": int(time.time() * 1000),
                        "title": title,
                        "filename": safe_filename,
                        "isInitial": False
                    }
                    
                    # Update DB
                    data = []
                    if os.path.exists(DB_FILE):
                        with open(DB_FILE, 'r') as f:
                            data = json.load(f)
                    data.insert(0, new_item)
                    with open(DB_FILE, 'w') as f:
                        json.dump(data, f, indent=4)
                    
                    self.send_response(201)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    self.wfile.write(json.dumps(new_item).encode('utf-8'))
                else:
                    self.send_error(400, "No image data found")
            except Exception as e:
                print(f"[!] Upload Error: {e}")
                self.send_error(500, str(e))

    def do_DELETE(self):
        if self.path.startswith('/api/gallery/'):
            try:
                item_id = int(self.path.split('/')[-1])
                with open(DB_FILE, 'r') as f:
                    data = json.load(f)
                
                item = next((x for x in data if x['id'] == item_id), None)
                if item:
                    # Delete file if it's an upload
                    if not item.get('isInitial'):
                        file_path = os.path.join(UPLOADS_DIR, item['filename'])
                        if os.path.exists(file_path):
                            os.remove(file_path)
                    
                    data = [x for x in data if x['id'] != item_id]
                    with open(DB_FILE, 'w') as f:
                        json.dump(data, f, indent=4)
                    
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    self.wfile.write(json.dumps({"success": True}).encode())
                else:
                    self.send_error(404, "Item not found")
            except Exception as e:
                self.send_error(500, str(e))

    def log_message(self, format, *args):
        # Clean console output
        sys.stderr.write("%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), format%args))

class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    allow_reuse_address = True

if __name__ == '__main__':
    init_db()
    print(f"\n[UDEC BACKEND] Starting at http://localhost:{PORT}")
    print(f"[*] Website Dir: {WEBSITE_DIR}")
    print(f"[*] Uploads Dir: {UPLOADS_DIR}")
    
    try:
        # Explicitly use 0.0.0.0 for better compatibility on Windows
        with ThreadingTCPServer(("0.0.0.0", PORT), GalleryHandler) as httpd:
            httpd.serve_forever()
    except OSError as e:
        if e.errno == 98 or e.errno == 10048:
            print(f"[FATAL] Port {PORT} is already in use. Is another instance running?")
        else:
            print(f"[FATAL] Server Error: {e}")
        sys.exit(1)
    except KeyboardInterrupt:
        print("\n[!] Stopping backend...")
        sys.exit(0)
    except Exception as e:
        print(f"[FATAL] Unexpected Error: {e}")
        sys.exit(1)
