import SimpleHTTPServer
import SocketServer
import json
import urlparse
import subprocess

PORT = 8000

class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        parsed_path = urlparse.urlparse(self.path)
        if parsed_path.path == "/api/v1/images/recognize":
            try:
                # Run the captcha_recognize_single.py script
                process = subprocess.Popen(['python', 'captcha_recognize_single.py'],
                                           stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                stdout, stderr = process.communicate()

                if process.returncode != 0:
                    response_data = {
                        "message": "Error running the script",
                        "status": "error",
                        "error": stderr.decode('utf-8')
                    }
                    self.send_response(500)
                else:
                    # Assuming the script produces JSON output
                    try:
                        response_data = json.loads(stdout.decode('utf-8'))
                        self.send_response(200)
                    except ValueError:
                        response_data = {
                            "message": "Script output is not valid JSON 2",
                            "status": "error"
                        }
                        self.send_response(500)

                response_data = {
                    "message": stdout.decode('utf-8'),
                    "status": "error"
                }
                self.send_response(200)


                # Send headers
                self.send_header("Content-type", "application/json")
                self.end_headers()

                # Write the JSON response
                self.wfile.write(json.dumps(response_data))
            except Exception as e:
                response_data = {
                    "message": "Exception occurred",
                    "status": "error",
                    "error": str(e)
                }

                # Send response status code
                self.send_response(500)

                # Send headers
                self.send_header("Content-type", "application/json")
                self.end_headers()

                # Write the JSON response
                self.wfile.write(json.dumps(response_data))
        else:
            # Handle other paths or send a 404 response
            self.send_response(404)
            self.end_headers()
            self.wfile.write(parsed_path.path)
            self.wfile.write("Not Found")

# Set up the server
httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler)

print("serving at port", PORT)
httpd.serve_forever()
