import httpx
import os


async def process_pdf_logic(pdf_file):
    """
    接收 PDF 文件并转发到解析服务
    """
    # 验证文件类型
    if not pdf_file.content_type.startswith("application/pdf"):
        raise Exception(400, "仅支持 PDF 文件")

    try:
        # 读取文件内容
        # file_content = await pdf_file.read()
        
        # 配置目标接口参数
        target_url = os.getenv("Mineru_URL","http://172.18.30.122:9988")
        target_url = target_url + "/analyze-pdf"
        # target_url = os.getenv("Mineru_URL","http://172.18.127.124:9088/pdf_parse")
        # target_url = "http://172.18.30.122:8998/pdf_parse"
        # params = {
        #     "parse_method": "auto",
        #     "is_json_md_dump": "true",
        #     "output_dir": "output"
        # }
        
        # 构建文件上传格式
        files = {
            "file": (pdf_file.filename, pdf_file.file, "application/pdf")
            # "pdf_file": (pdf_file.filename, pdf_file.file, "application/pdf")
        }

        # 发送请求到解析服务
        async with httpx.AsyncClient(timeout=120.0) as client:
            response = await client.post(
                target_url,
                # params=params,
                files=files,
                headers={"Accept": "application/json"}
            )
            response.raise_for_status()
            result = response.json()
            
            content_list = result["data"]["full_content"]
            # markdown_content =""
            # for content in content_list:
            #     text = content["text"]

            return content_list

    except httpx.RequestError as e:
        raise Exception(503, f"无法连接到解析服务: {str(e)}")
    except Exception as e:
        raise Exception(500, f"服务器内部错误: {str(e)}")
    
if __name__ == "__main__":
    # 测试：传入 PDF 文件路径
    result = process_pdf_logic("邱茜茜.pdf")
    print(result)
    # with open("邱茜茜.md", "w", encoding="utf-8") as f:
    #     f.write(result)