from http.server import SimpleHTTPRequestHandler, HTTPServer
import json
import subprocess
from urllib.parse import urlparse
import re
import logging


PORT = 8601


class MyRequestHandler(SimpleHTTPRequestHandler):
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    def do_POST(self):
        parsed_path = urlparse(self.path)

        if parsed_path.path == "/api/v1/images/recognize":
            try:
                # Read the content of the request
                content_length = int(self.headers['Content-Length'])
                post_data = self.rfile.read(content_length)
                data = json.loads(post_data.decode('utf-8'))

                # Extract the base64 image data from the request
                if 'image' not in data:
                    self.send_response(400)
                    self.send_header("Content-type", "application/json")
                    self.end_headers()
                    response_data = {
                        "message": "No image found in request",
                        "status": "error"
                    }
                    self.wfile.write(json.dumps(response_data).encode('utf-8'))
                    return

                base64_image = data['image']

                self.logger.info("""image {0}""".format(base64_image))

                # Run the captcha_recognize_single.py script
                process = subprocess.Popen(
                    ['python', 'captcha_recognize_single3.py', base64_image],
                    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                stdout, stderr = process.communicate()

                if stderr:
                    self.logger.info("""Error: {}""".format(stderr.decode('utf-8')))
                result_text = stdout.decode('utf-8')

                if result_text == "":
                    return

                # Define the regex pattern to extract the number
                pattern = r'captcha_code_is:(\d+)'

                # Use re.search to find the match
                match = re.search(pattern, result_text)
                number = match.group(1)

                if process.returncode != 0:
                    response_data = {
                        "message": "Error running the script",
                        "status": "error",
                        "errors": stderr.decode('utf-8')
                    }
                    self.send_response(500)
                else:
                    # Assuming the script produces JSON output
                    try:
                        response_data = {
                            'results': number,
                            'message': 'successful',
                            'errors': [],
                        }
                        self.send_response(200)
                    except ValueError:
                        response_data = {
                            "message": "Script output is not valid JSON",
                            "status": "error",
                            "errors": [],
                        }
                        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).encode('utf-8'))
            except Exception as e:
                response_data = {
                    "message": "Exception occurred 99",
                    "status": "error",
                    "errors": 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).encode('utf-8'))
        else:
            # Handle other paths or send a 404 response
            self.send_response(404)
            self.send_header("Content-type", "text/plain")
            self.end_headers()
            self.wfile.write(b"Not Found")


def main():
    # Set up the server
    httpd = HTTPServer(("", PORT), MyRequestHandler)

    # print(f"Serving at port {PORT}")

    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    logger.info("Serving at port %d", PORT)

    httpd.serve_forever()


if __name__ == '__main__':
    main()
