from anyio import Path
from fastapi import HTTPException
from lxml import etree  # type: ignore
from weasyprint import HTML  # type: ignore


async def get_parsable_ids():
    parsable_files_dir = await Path('/app/apps/remd/xls').resolve()
    parsable_ids: list[str] = [
        file.name.split('.')[0]
        async for file in parsable_files_dir.iterdir()
        if await file.is_file()
    ]

    return parsable_ids


async def convert_aemd_to_pdf(xml_str: bytes, docKind: str):
    xml = etree.fromstring(xml_str)  # type: ignore
    xsl = etree.parse(f'/app/apps/remd/xls/{docKind}.xsl')  # type: ignore
    transform = etree.XSLT(xsl)  # type: ignore

    html = transform(xml)  # type: ignore
    html_str = etree.tostring(  # type: ignore
        html, pretty_print=True, encoding='unicode', method='html'
    )

    pdf = HTML(string=html_str).write_pdf()  # type: ignore

    if not pdf:
        raise HTTPException(status_code=500, detail='PDF not generated')

    return pdf
