import config
from db.schemas import Settings
from utils import (
    logger,
    requestGET,
    requestPOSTMultipart,
    answer,
    detect_and_save_attachment,
    requestPOST,
)
from pathlib import Path


def getVerifySSL(url: str):
    return "demo" not in url.lower()


# TODO Проработать лимит в 50 запросов за 15 минут


async def sendForSigning(inData: dict):
    settings = await Settings.getSettings(False)
    if not settings.success:
        logger.error("Настройки не инициализированы")
        return answer(success=False, message="Настройки не инициализированы")
    settings = settings.data
    meta = {
        "organization": {
            "idLpu": settings.n3healthXIdLpu,
        },
        "practitioner": inData.get("practitioner", {}),
        "patients": inData.get("patients", {}),
        "medDocument": inData.get("medDocument", {}),
        "delivery": ["sms"],
    }

    headers = {
        "Authorization": settings.n3healthAutorization,
        "X-Id-Lpu": settings.n3healthXIdLpu,
    }

    response = await requestPOSTMultipart(
        url=f"{settings.n3healthHost}/signing",
        headers=headers,
        meta=meta,
        files=inData.get("files", []),
        verify_ssl=getVerifySSL(settings.n3healthHost),
    )
    return response


async def resend(trackingID: str, IdPatientMis: str):
    settings = await Settings.getSettings(False)
    if not settings.success:
        logger.error("Настройки не инициализированы")
        return answer(success=False, message="Настройки не инициализированы")
    settings = settings.data
    headers = {
        "Authorization": settings.n3healthAutorization,
        "X-Id-Lpu": settings.n3healthXIdLpu,
    }
    data = {
        "trackingId": trackingID,
        "IdPatientMis": [str(IdPatientMis)],
        "delivery": ["sms"],
    }
    response = await requestPOST(
        f"{settings.n3healthHost}/resend",
        headers=headers,
        json=data,
        verify_ssl=getVerifySSL(settings.n3healthHost),
    )

    logger.warning(response)

    return response


async def revoke(trackingID: str):
    settings = await Settings.getSettings(False)
    if not settings.success:
        logger.error("Настройки не инициализированы")
        return answer(success=False, message="Настройки не инициализированы")
    settings = settings.data
    headers = {
        "Authorization": settings.n3healthAutorization,
        "X-Id-Lpu": settings.n3healthXIdLpu,
    }
    response = await requestPOST(
        f"{settings.n3healthHost}/signing/{trackingID}/cancel",
        headers=headers,
        verify_ssl=getVerifySSL(settings.n3healthHost),
    )
    return response


async def checkConnection(host: str, authorization: str, xIdLpu: str):
    headers = {"Authorization": authorization, "X-Id-Lpu": xIdLpu}
    params = {
        "limit": 1,
        "offset": 0,
    }
    return await requestGET(
        f"{host}/signing",
        headers=headers,
        params=params,
        verify_ssl=getVerifySSL(host),
    )


async def getAllSigning():
    settings = await Settings.getSettings(False)
    if not settings.success:
        logger.error("Настройки не инициализированы")
        return answer(success=False, message="Настройки не инициализированы")
    apiUrl = settings.data.n3healthHost
    path = "/signing"
    headers = {"Authorization": config.N3_KEY, "X-Id-Lpu": config.N3_ID}
    response = await requestGET(apiUrl + path, headers=headers, verify_ssl=False)
    logger.info(response)
    return response


async def getMisIdSigning(idPatientMis: str):
    apiUrl = config.N3_URL
    path = "/signing"
    headers = {"Authorization": config.N3_KEY, "X-Id-Lpu": config.N3_ID}
    parameters = {"idPatientMis": idPatientMis}
    response = await requestGET(
        apiUrl + path, headers=headers, params=parameters, verify_ssl=False
    )
    logger.info(response)
    return response


async def getTrackingIDSigning(trackingID: str, latestStatusCode: int, singingId: int):
    settings = await Settings.getSettings(False)
    if not settings.success:
        logger.error("Настройки не инициализированы")
        return answer(success=False, message="Настройки не инициализированы")
    apiUrl = settings.data.n3healthHost
    path = f"/signing/{trackingID}"
    headers = {
        "Authorization": settings.data.n3healthAutorization,
        "X-Id-Lpu": settings.data.n3healthXIdLpu,
    }
    response = await requestGET(
        apiUrl + path, headers=headers, verify_ssl=getVerifySSL(apiUrl)
    )

    if not response.success:
        logger.error(response.message)
        return response

    patients = response.data.get("data", {}).get("patients", [])

    status = {"code": 0, "description": ""}

    patientsIds = []

    for patient in patients:
        patientsIds.append(patient["idPatientMis"])
        if patient.get("status", {}).get("code", 0) > status["code"]:
            status = patient.get("status", {})

    message = "Файлы успешно сохранены"

    if latestStatusCode != status["code"]:

        attachments = (
            response.data.get("data", {}).get("medDocument", {}).get("attachments", [])
        )

        if len(attachments) > 0:

            for idx, attachment in enumerate(attachments, start=1):
                content = attachment.get("content")
                if not content:
                    continue

                ATTACHMENTS_DIR = Path("src/attachments/import")

                for patientId in patientsIds:

                    result = detect_and_save_attachment(
                        b64_content=content,
                        output_dir=ATTACHMENTS_DIR / patientId / str(singingId),
                        filename_prefix=f"document_{idx}",
                        save_attachments=True,
                    )

                    if not result:
                        logger.error("Файлы не сохранены")
                        message = "Файлы не сохранены"
                    else:
                        status["storagePath"] = str(result["path"])

    return answer(data=status, message=message)
