import os
import mimetypes

class Router:
    def __init__(self):
        self.routes = {
            'GET': {},
            'POST': {},
            'PUT': {},
            'DELETE': {}
        }

    def get(self, path, handler):
        self._add_route(path, handler, ['GET'])

    def post(self, path, handler):
        self._add_route(path, handler, ['POST'])

    def put(self, path, handler):
        self._add_route(path, handler, ['PUT'])

    def delete(self, path, handler):
        self._add_route(path, handler, ['DELETE'])

    def _add_route(self, path, handler, methods):
        for method in methods:
            self.routes[method][path] = handler

    def dispatch(self, request):
        return self.route_request(
            request.path,
            request.method,
            request.body
        )

    def route_request(self, path, method, body=None):
        handler = self.routes.get(method, {}).get(path)

        if handler:
            return handler(body)

        if method == 'GET':
            return self.serve_static_asset(path)

        return Response(
            body=b"404 Route Not Found",
            status="404 Not Found",
            headers=[("Content-Type", "text/plain")]
        )

    def serve_static_asset(self, path):

        static_dir = os.path.join(os.getcwd(), "public")
        clean_path = path.replace("/public/", "").lstrip("/")
        asset_path = os.path.join(static_dir, clean_path)

        if os.path.isfile(asset_path):

            mime_type, _ = mimetypes.guess_type(asset_path)

            with open(asset_path, 'rb') as f:
                content = f.read()

            return {
                "status": "200 OK",
                "headers": [
                    ("Content-Type", mime_type or "application/octet-stream")
                ],
                "body": content
            }

        return {
            "status": "404 Not Found",
            "headers": [("Content-Type", "text/plain")],
            "body": b"File not found"
        }