import webview
import os
import sys
from http.server import HTTPServer, SimpleHTTPRequestHandler
import threading

def get_dist_path():
    if getattr(sys, 'frozen', False):
        base_path = sys._MEIPASS
    else:
        base_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    
    dist_path = os.path.join(base_path, 'dist')
    print(f"Dist path: {dist_path}")
    return dist_path

class CustomHandler(SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        dist_dir = get_dist_path()
        print(f"Serving from directory: {dist_dir}")
        super().__init__(*args, directory=dist_dir, **kwargs)
    
    def log_message(self, format, *args):
        # Override to show more detailed logging
        print(f"Request: {format%args}")
        if hasattr(self, 'path'):
            print(f"Requested path: {self.path}")
            full_path = os.path.join(self.directory, self.path.lstrip('/'))
            print(f"Full path: {full_path}")
            print(f"File exists: {os.path.exists(full_path)}")
            if self.path.endswith('.html'):
                print(f"HTML content: {open(full_path).read()[:200]}...")

def run_server(port=8000):
    server_address = ('localhost', port)
    httpd = HTTPServer(server_address, CustomHandler)
    print(f"Serving files from {get_dist_path()} at http://localhost:{port}")
    httpd.serve_forever()

def main():
    dist_path = get_dist_path()
    
    # Start local server
    server_thread = threading.Thread(target=run_server)
    server_thread.daemon = True
    server_thread.start()
    
    # Create window using local server
    window = webview.create_window(
        'TimeSafari',
        url='http://localhost:8000',
        width=1200,
        height=800
    )
    
    webview.start(debug=True)

if __name__ == '__main__':
    main() 