# 文件路径及文件名: laybot_ai/file.py
# 简要阐述该文件的作用: 封装文件上传、下载、保存、查询、删除等能力，供 Batch 与其他文件类接口复用。

from __future__ import annotations
from pathlib import Path

from .client import Client
from .exceptions import ValidationError


class File:
    def __init__(self, api_key: str | Client, *, vendor="laybot", base=None):
        self.cli = api_key if isinstance(api_key, Client) \
            else Client(api_key, vendor=vendor, base=base)

    def upload(self, path: str, purpose="batch", mime_type="application/jsonl") -> dict:
        fp = Path(path)
        if not fp.is_file():
            raise ValidationError(f"{path} not found")

        with fp.open("rb") as f:
            resp = self.cli.post_multipart(
                "/v1/files",
                files={"file": (fp.name, f, mime_type)},
                data={"purpose": purpose},
            )
        return resp.json()

    def retrieve(self, file_id: str) -> dict:
        return self.cli.get(f"/v1/files/{file_id}").json()

    def download(self, file_id: str) -> str:
        return self.cli.get(f"/v1/files/{file_id}/content").text

    def download_bytes(self, file_id: str) -> bytes:
        return self.cli.get(f"/v1/files/{file_id}/content").content

    def download_to(self, file_id: str, save_path: str) -> str:
        data = self.download_bytes(file_id)
        fp = Path(save_path)
        fp.parent.mkdir(parents=True, exist_ok=True)
        fp.write_bytes(data)
        return str(fp)

    def delete(self, file_id: str) -> dict:
        return self.cli.delete(f"/v1/files/{file_id}").json()
