# src/content_understanding_client/client.py

import json
import time
import logging
import requests


class ContentUnderstandingClient:
    def __init__(self, endpoint: str, api_key: str, api_version: str):
        logging.info("Initializing ContentUnderstandingClient")
        if not endpoint or not api_key or not api_version:
            raise ValueError("endpoint, api_key, and api_version are required")

        self.endpoint = endpoint.rstrip("/")
        self.api_key = api_key
        self.api_version = api_version
        self.base_headers = {
            "Ocp-Apim-Subscription-Key": api_key,
        }

    def begin_analyze(self, analyzer_id: str, file_bytes: bytes):
        analyze_url = (
            f"{self.endpoint}/contentunderstanding/analyzers/"
            f"{analyzer_id}:analyze?api-version={self.api_version}"
        )

        headers = {
            "Content-Type": "application/octet-stream",
            **self.base_headers,
        }

        response = requests.post(analyze_url, headers=headers, data=file_bytes)
        response.raise_for_status()

        operation_location = response.headers.get("operation-location")
        if not operation_location:
            raise RuntimeError("operation-location header missing")

        return operation_location

    def poll_result(
        self,
        operation_location: str,
        polling_interval_seconds: int = 2,
    ):
        while True:
            response = requests.get(
                operation_location, headers=self.base_headers
            )
            response.raise_for_status()

            result = response.json()
            status = result.get("status", "").lower()

            if status == "succeeded":
                return result
            if status == "failed":
                raise RuntimeError(
                    f"Analysis failed: {json.dumps(result, indent=2)}"
                )

            time.sleep(polling_interval_seconds)
