#!/usr/bin/env python3
"""
BB10 Chat Web Application
Simple HTTP server for BB10 Chat interface
Serves static files directly - chat communication goes directly to chat.php
"""

import http.server
import socketserver
import json
import urllib.request
import urllib.parse
import urllib.error
import ssl
import os
import sys

PORT = 8025
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CHAT_API = 'https://berrystore.sw7ft.com/apps/chat.php'

class BB10ChatHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=BASE_DIR, **kwargs)
    
    def do_GET(self):
        """Handle GET requests for static files and API proxy"""
        if '?' in self.path:
            path, query_string = self.path.split('?', 1)
        else:
            path = self.path
            query_string = ''
        
        # Handle API proxy calls
        if path.startswith('/api'):
            print(f"API request: path='{path}', query='{query_string}'")
            self.handle_api_proxy('GET', query_string)
        # Serve main page
        elif path == '/' or path == '/index.html':
            self.serve_file('index.html', 'text/html')
        # Serve favicon
        elif path == '/favicon.ico':
            self.serve_favicon()
        # Serve other static files
        elif path.endswith('.css'):
            self.serve_file(path[1:], 'text/css')
        elif path.endswith('.js'):
            self.serve_file(path[1:], 'application/javascript')
        elif path.endswith('.png'):
            self.serve_file(path[1:], 'image/png')
        elif path.endswith('.jpg') or path.endswith('.jpeg'):
            self.serve_file(path[1:], 'image/jpeg')
        else:
            self.send_error(404, f"File not found: {path}")
    
    def do_POST(self):
        """Handle POST requests for API proxy"""
        if self.path.startswith('/api'):
            self.handle_api_proxy('POST', '')
        else:
            self.send_error(404, "Not found")
    
    def serve_file(self, file_path, content_type):
        """Serve static files from the app directory"""
        full_path = os.path.join(BASE_DIR, file_path)
        try:
            if content_type.startswith('image/'):
                with open(full_path, 'rb') as f:
                    content = f.read()
                self.send_response(200)
                self.send_header('Content-type', content_type)
                self.send_header('Cache-Control', 'public, max-age=86400')
                self.end_headers()
                self.wfile.write(content)
            else:
                with open(full_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                self.send_response(200)
                self.send_header('Content-type', content_type)
                self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
                self.send_header('Pragma', 'no-cache')
                self.send_header('Expires', '0')
                self.end_headers()
                self.wfile.write(content.encode('utf-8'))
        except FileNotFoundError:
            self.send_error(404, f"File not found: {file_path}")
        except Exception as e:
            self.send_error(500, f"Error serving file: {str(e)}")
    
    def handle_api_proxy(self, method, query_string):
        """Proxy API requests to the chat.php endpoint"""
        try:
            # Create SSL context that doesn't verify certificates
            ssl_context = ssl.create_default_context()
            ssl_context.check_hostname = False
            ssl_context.verify_mode = ssl.CERT_NONE
            
            if method == 'GET':
                url = f"{CHAT_API}?{query_string}"
                print(f"Proxying GET to: {url}")
                print(f"Query string: '{query_string}'")
                
                # Create request with proper headers
                req = urllib.request.Request(url)
                req.add_header('User-Agent', 'Mozilla/5.0 (BB10; Kbd) AppleWebKit/537.35+ (KHTML, like Gecko) Version/10.3.3.3216 Mobile Safari/537.35+')
                req.add_header('Accept', 'application/json, text/plain, */*')
                req.add_header('Accept-Language', 'en-US,en;q=0.9')
                
                with urllib.request.urlopen(req, context=ssl_context) as response:
                    data = response.read().decode('utf-8')
                    print(f"Response length: {len(data)}")
                    print(f"Response preview: {data[:200]}...")
                    
            elif method == 'POST':
                content_length = int(self.headers.get('Content-Length', 0))
                post_data = self.rfile.read(content_length) if content_length > 0 else b''
                
                print(f"Proxying POST to: {CHAT_API}")
                print(f"POST data: {post_data.decode('utf-8') if post_data else 'No data'}")
                
                req = urllib.request.Request(
                    CHAT_API,
                    data=post_data,
                    headers={'Content-Type': 'application/json'}
                )
                
                with urllib.request.urlopen(req, context=ssl_context) as response:
                    data = response.read().decode('utf-8')
            
            # Return the proxied response
            print(f"Sending response length: {len(data)}")
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Content-Length', str(len(data.encode('utf-8'))))
            self.send_header('Cache-Control', 'no-cache')
            self.end_headers()
            self.wfile.write(data.encode('utf-8'))
            print(f"Response sent successfully")
            
        except Exception as e:
            print(f"API proxy error: {e}")
            self.send_response(500)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            error_response = json.dumps({
                "success": False,
                "error": f"Proxy error: {str(e)}"
            })
            self.wfile.write(error_response.encode('utf-8'))
    
    def serve_favicon(self):
        """Serve a simple favicon to avoid 404 errors"""
        # Simple 16x16 transparent favicon
        favicon_data = (
            b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00'
            b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00\x08'
            b'\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01'
            b'\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x80\x80\x80\x00' + b'\x00' * 1000
        )
        
        self.send_response(200)
        self.send_header('Content-Type', 'image/x-icon')
        self.send_header('Cache-Control', 'public, max-age=86400')
        self.end_headers()
        self.wfile.write(favicon_data)

    def log_message(self, format, *args):
        """Override to provide cleaner logging"""
        print(f"[{self.address_string()}] {format % args}")

if __name__ == "__main__":
    try:
        print(f"BB10 Chat starting on port {PORT}")
        print(f"Base directory: {BASE_DIR}")
        print(f"Access via: http://localhost:{PORT}")
        print(f"API Proxy: {CHAT_API}")
        
        os.chdir(BASE_DIR)
        
        with socketserver.TCPServer(("", PORT), BB10ChatHandler) as httpd:
            print(f"BB10 Chat server running on port {PORT}")
            print("Press Ctrl+C to stop the server")
            httpd.serve_forever()
    except KeyboardInterrupt:
        print("\nBB10 Chat server stopped")
    except Exception as e:
        print(f"Error starting server: {e}")
        sys.exit(1) 