Investment Plans workspace
Open raw ↗
import http.server
import socketserver
import json
import os
import urllib.parse
from database import init_db, get_connection

PORT = 8080
DIRECTORY = os.path.join(os.path.dirname(__file__), "static")

class HADRequestHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

    def do_GET(self):
        # Basic API Routing
        if self.path == '/api/health':
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            response = {"status": "ok", "service": "HAD Digital API"}
            self.wfile.write(json.dumps(response).encode())
            return
            
        elif self.path.startswith('/api/reports'):
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            
            conn = get_connection()
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM toxicity_reports ORDER BY created_at DESC LIMIT 10")
            reports = [dict(row) for row in cursor.fetchall()]
            conn.close()
            
            self.wfile.write(json.dumps({"reports": reports}).encode())
            return

        # Fallback to static files
        return super().do_GET()

    def do_POST(self):
        if self.path == '/api/reports':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            
            try:
                data = json.loads(post_data.decode('utf-8'))
                patient_id = data.get('patient_id', 1) # Mock default
                report_data = json.dumps(data.get('symptoms', {}))
                
                # Mock grading logic (to be replaced by CTCAE engine)
                computed_grade = data.get('mock_grade', 1)
                
                conn = get_connection()
                cursor = conn.cursor()
                cursor.execute(
                    "INSERT INTO toxicity_reports (patient_id, report_data, computed_grade) VALUES (?, ?, ?)",
                    (patient_id, report_data, computed_grade)
                )
                conn.commit()
                conn.close()
                
                self.send_response(201)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"status": "success", "message": "Report saved"}).encode())
                
            except Exception as e:
                self.send_response(400)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"status": "error", "message": str(e)}).encode())
            return

def start_server():
    init_db() # Ensure DB exists before starting
    
    # Ensure static directory exists
    if not os.path.exists(DIRECTORY):
        os.makedirs(DIRECTORY)
        with open(os.path.join(DIRECTORY, "index.html"), "w") as f:
            f.write("<h1>HAD Digital - Embedded Server Running</h1>")

    with socketserver.TCPServer(("", PORT), HADRequestHandler) as httpd:
        print(f"Serving HAD Digital MVP on http://localhost:{PORT}")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nShutting down server.")

if __name__ == '__main__':
    start_server()