import asyncio
import logging
from aiohttp import web
from aiohttp.http_exceptions import BadStatusLine
import os

class _BadStatusLineFilter(logging.Filter):
    """Suprime log quando cliente conecta via HTTPS na porta HTTP (TLS ClientHello)."""

    def filter(self, record: logging.LogRecord) -> bool:
        if record.exc_info and record.exc_info[0]:
            if issubclass(record.exc_info[0], BadStatusLine):
                return False
        msg = record.getMessage()
        if "BadStatusLine" in msg or "Invalid method" in msg:
            return False
        return True


logging.getLogger("aiohttp.server").addFilter(_BadStatusLineFilter())


@web.middleware
async def js_mime_middleware(request: web.Request, handler):
    """Garante que .js seja servido como application/javascript (Safari exige)."""
    response = await handler(request)
    if request.path.endswith('.js'):
        response.headers['Content-Type'] = 'application/javascript; charset=utf-8'
    return response


class ExploiterWebServer:
    def __init__(self, host: str, port: int, exploit_templates_dir: str, static_files_dir: str):
        self.host = host
        self.port = port
        self.exploit_templates_dir = exploit_templates_dir
        self.static_files_dir = static_files_dir
        self.app = web.Application(middlewares=[js_mime_middleware])
        self._setup_routes()
        self.runner = None
        self.site = None

    def _setup_routes(self):
        if os.path.isdir(self.static_files_dir):
            self.app.router.add_static("/static/", path=self.static_files_dir, name="static")

        coruna_dir = os.path.join(self.exploit_templates_dir, "coruna")
        if not os.path.isdir(coruna_dir):
            self.app.router.add_get('/', self._handle_no_coruna)
            return
        self.app.router.add_static('/coruna/', path=coruna_dir, name='coruna')
        self.app.router.add_get('/', self._handle_coruna_redirect)
        self.app.router.add_get('/coruna', self._handle_coruna_redirect)

    async def _handle_no_coruna(self, _request: web.Request):
        return web.Response(
            text="<h1>Coruna not configured</h1><p>Missing exploits/coruna/ directory.</p>",
            status=503,
            content_type='text/html',
        )

    async def _handle_coruna_redirect(self, _request: web.Request):
        raise web.HTTPFound('/coruna/group.html')

    async def start(self, config_manager_instance):
        # Acessar a instância do ConfigManager via app['config']
        self.app['config'] = config_manager_instance 
        
        self.runner = web.AppRunner(self.app)
        await self.runner.setup()
        self.site = web.TCPSite(self.runner, self.host, self.port)
        await self.site.start()
        print(f"[*] Web Server de Exploit ouvindo em http://{self.host}:{self.port}...")

    async def stop(self):
        if self.site:
            await self.site.stop()
        if self.runner:
            await self.runner.cleanup()
        print("[*] Web Server de Exploit desligado.")