import json
import logging
from typing import Optional

from pydantic import BaseModel

from models import ResultModel

logger = logging.getLogger(__name__)


class RequestBodyModel(BaseModel):
    path: str
    data: str
    headers: str


def parse_request_body(body: str) -> Optional[RequestBodyModel]:
    if not body:
        return None
    parts = body.split("\n", maxsplit=2)
    if len(parts) == 3:
        return RequestBodyModel(
            path=parts[0].strip("/"), headers=parts[1], data=parts[2]
        )
    else:
        logger.error(f"指令格式错误：{body}")
        return None


def format_response_body(consume_result: ResultModel):
    responseBody = f"{consume_result.code}\n{consume_result.message}"
    if consume_result.code == 200 and consume_result.data is not None:
        try:
            response_headers = json.dumps(
                {},
                default=lambda o: o.__dict__,
                ensure_ascii=False,
            )
            response_data = json.dumps(
                consume_result.data,
                default=lambda o: o.__dict__,
                ensure_ascii=False,
            )
            responseBody = f"{consume_result.code}\n{response_headers}\n{response_data}"
        except Exception as e:
            logger.exception(f"json encode error:{consume_result.data} {e}")
    return responseBody
