import http.server
import os
import traceback

SAVE_DIR = os.path.join(os.path.expanduser("~"), "Desktop", "Received_Files")
os.makedirs(SAVE_DIR, exist_ok=True)

class FileReceiver(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        try:
            if self.path == '/upload':
                content_type = self.headers.get('Content-Type', '')
                content_length = int(self.headers.get('Content-Length', 0))

                if 'multipart/form-data' in content_type:
                    boundary = content_type.split('boundary=')[1].strip().encode()

                    # Read all data in chunks
                    body = b''
                    remaining = content_length
                    while remaining > 0:
                        chunk_size = min(65536, remaining)
                        chunk = self.rfile.read(chunk_size)
                        if not chunk:
                            break
                        body += chunk
                        remaining -= len(chunk)

                    # Parse multipart
                    delimiter = b'--' + boundary
                    parts = body.split(delimiter)

                    saved = 0
                    for part in parts:
                        if b'filename=' in part and b'\r\n\r\n' in part:
                            header_section, _, file_content = part.partition(b'\r\n\r\n')
                            
                            # Extract filename
                            filename = 'received_file'
                            for line in header_section.split(b'\r\n'):
                                if b'filename=' in line:
                                    try:
                                        filename = line.split(b'filename=')[1].strip().strip(b'"').decode('utf-8')
                                    except:
                                        filename = f'file_{saved+1}'

                            # Remove trailing boundary markers
                            file_content = file_content.rstrip(b'\r\n--')

                            if file_content:
                                save_path = os.path.join(SAVE_DIR, filename)
                                with open(save_path, 'wb') as f:
                                    f.write(file_content)
                                print(f"✅ Saved: {filename} ({len(file_content):,} bytes)")
                                saved += 1

                    # Send response AFTER saving
                    self.send_response(200)
                    self.send_header('Content-Type', 'text/plain')
                    self.send_header('Content-Length', '2')
                    self.send_header('Connection', 'close')
                    self.end_headers()
                    self.wfile.write(b'OK')
                    self.wfile.flush()

                else:
                    self.send_response(400)
                    self.end_headers()
            else:
                self.send_response(404)
                self.end_headers()

        except Exception as e:
            print(f"❌ Error: {e}")
            traceback.print_exc()
            try:
                self.send_response(500)
                self.end_headers()
            except:
                pass

    def log_message(self, format, *args):
        pass  # Silent

class ThreadedServer(http.server.ThreadingHTTPServer):
    pass

print("🚀 Olii-8882 WiFi Receiver running on port 9999")
print(f"📁 Saving to: {SAVE_DIR}")
print("Press Ctrl+C to stop\n")

server = ThreadedServer(('0.0.0.0', 9999), FileReceiver)
server.serve_forever()
