"""Factur-X Engine Python SDK — thin wrapper around the REST API."""
import requests
from pathlib import Path
from typing import Optional, Union


class FacturxEngine:
    """Client for the Factur-X Engine REST API."""

    def __init__(self, base_url: str = "http://localhost:8000"):
        self.base_url = base_url.rstrip("/")
        self._session = requests.Session()

    def health(self) -> dict:
        r = self._session.get(f"{self.base_url}/health")
        r.raise_for_status()
        return r.json()

    def generate_xml(self, metadata: dict) -> bytes:
        import json
        r = self._session.post(
            f"{self.base_url}/v1/xml",
            data={"metadata": json.dumps(metadata)},
        )
        r.raise_for_status()
        return r.content

    def validate(self, file_path: Union[str, Path]) -> dict:
        p = Path(file_path)
        with open(p, "rb") as f:
            r = self._session.post(
                f"{self.base_url}/v1/validate",
                files={"file": (p.name, f)},
            )
        r.raise_for_status()
        return r.json()

    def convert(self, pdf_path: Union[str, Path], metadata: dict) -> bytes:
        import json
        p = Path(pdf_path)
        with open(p, "rb") as f:
            r = self._session.post(
                f"{self.base_url}/v1/convert",
                files={"pdf": (p.name, f)},
                data={"metadata": json.dumps(metadata)},
            )
        r.raise_for_status()
        return r.content

    def merge(self, pdf_path: Union[str, Path], xml_path: Union[str, Path], format: Optional[str] = None) -> bytes:
        pp, px = Path(pdf_path), Path(xml_path)
        with open(pp, "rb") as fp, open(px, "rb") as fx:
            data = {"format": format} if format else {}
            r = self._session.post(
                f"{self.base_url}/v1/merge",
                files={"pdf": (pp.name, fp), "xml": (px.name, fx)},
                data=data,
            )
        r.raise_for_status()
        return r.content

    def extract(self, pdf_path: Union[str, Path]) -> dict:
        p = Path(pdf_path)
        with open(p, "rb") as f:
            r = self._session.post(
                f"{self.base_url}/v1/extract",
                files={"file": (p.name, f)},
            )
        r.raise_for_status()
        return r.json()
