"""WSGI adapter for Prisca's existing lightweight HTTP handler."""
import io
from email.message import Message
from app import H, init_db, seed_excel, seed_rainwood, normalize_price_categories, seed_cabs, load_integration_env

init_db(); seed_excel(); seed_rainwood(); normalize_price_categories(); seed_cabs(); load_integration_env()

class FakeHandler:
    def __init__(self,environ,start_response):
        self.path=environ.get('PATH_INFO','/')
        if environ.get('QUERY_STRING'): self.path += '?'+environ['QUERY_STRING']
        self.headers=Message()
        for k,v in environ.items():
            if k.startswith('HTTP_'): self.headers[k[5:].replace('_','-')]=v
        if 'CONTENT_TYPE' in environ:self.headers['Content-Type']=environ['CONTENT_TYPE']
        if 'CONTENT_LENGTH' in environ:self.headers['Content-Length']=environ['CONTENT_LENGTH']
        self.rfile=io.BytesIO(environ.get('wsgi.input').read(int(environ.get('CONTENT_LENGTH') or 0)))
        self.wfile=io.BytesIO(); self.status='200 OK'; self.response_headers=[]; self.start_response=start_response
    def send_response(self,code,message=None):
        reasons={200:'OK',201:'Created',204:'No Content',400:'Bad Request',401:'Unauthorized',403:'Forbidden',404:'Not Found',409:'Conflict',500:'Internal Server Error',502:'Bad Gateway'}
        self.status=f'{code} {message or reasons.get(code,"")}'.strip()
    def send_header(self,k,v): self.response_headers.append((k,v))
    def end_headers(self): pass
    def send_error(self,code,message=None):
        self.send_response(code,message); self.send_header('Content-Type','text/plain; charset=utf-8'); self.end_headers(); self.wfile.write((message or 'Not found').encode())

def application(environ,start_response):
    h=FakeHandler(environ,start_response)
    try:
        if environ.get('REQUEST_METHOD','GET').upper()=='POST': H.do_POST(h)
        else: H.do_GET(h)
    except Exception as e:
        h=FakeHandler(environ,start_response); h.send_response(500); h.send_header('Content-Type','application/json'); h.end_headers(); h.wfile.write((('{"error":"'+str(e).replace('"','\\"')+'"}')).encode())
    headers=list(h.response_headers)
    if not any(k.lower()=='content-length' for k,v in headers): headers.append(('Content-Length',str(len(h.wfile.getvalue()))))
    start_response(h.status,headers)
    return [h.wfile.getvalue()]
