import http.server
import socketserver
import sys
import urllib.parse
import os
import subprocess

class CORSRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Range')
        self.send_header('Access-Control-Expose-Headers', 'Content-Length, Content-Range')
        self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
        return super(CORSRequestHandler, self).end_headers()

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

    def do_GET(self):
        parsed_path = urllib.parse.urlparse(self.path)
        query = urllib.parse.parse_qs(parsed_path.query)
        
        # If start and end are provided, slice the audio
        if 'start' in query and 'end' in query:
            try:
                start_time = float(query['start'][0])
                end_time = float(query['end'][0])
                
                # Remove leading slash for local path
                filepath = urllib.parse.unquote(parsed_path.path).lstrip('/')
                
                if os.path.exists(filepath):
                    # Use ffmpeg to slice the audio and stream it
                    command = [
                        'ffmpeg', '-y', 
                        '-i', filepath, 
                        '-ss', str(start_time), 
                        '-to', str(end_time), 
                        '-f', 'wav', 
                        '-'
                    ]
                    
                    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
                    audio_data, _ = process.communicate()
                    
                    self.send_response(200)
                    self.send_header('Content-type', 'audio/wav')
                    self.send_header('Content-Length', str(len(audio_data)))
                    self.end_headers()
                    self.wfile.write(audio_data)
                    return
            except Exception as e:
                print(f"Error serving trimmed audio: {e}")
                
        # Fallback to normal behavior
        return super().do_GET()

if __name__ == '__main__':
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8081
    print(f"Starting CORS-enabled server on http://localhost:{port}")
    
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(("", port), CORSRequestHandler) as httpd:
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nShutting down server.")
