import anthropic as anthropic_sdk
from archo.llm.prompt import SYSTEM_PROMPT
from archo.llm.providers.llm_base import LLMProvider
from archo.schemas.architecture import ArchitectureResponse


class AnthropicProvider(LLMProvider):
    def __init__(self, api_key: str, model: str):
        self.api_key = api_key
        self.client = anthropic_sdk.Anthropic(api_key=self.api_key)
        self.model = model

    def call(self, file_bundle: str) -> ArchitectureResponse:
        """Send file bundle to Anthropic and return response text."""
        print(f"Sending to Anthropic ({self.model})...")

        try:
            with self.client.messages.stream(
                model=self.model,
                max_tokens=4096,
                system=SYSTEM_PROMPT,
                messages=[{"role": "user", "content": file_bundle}],
                output_format=ArchitectureResponse,
            ) as stream:
                response = stream.get_final_message()
        except anthropic_sdk.AuthenticationError:
            raise RuntimeError("Invalid API key — check LLM_API_KEY.")
        except anthropic_sdk.APIConnectionError:
            raise RuntimeError("Could not connect to Anthropic API — check your network.")
        except anthropic_sdk.APIStatusError as e:
            raise RuntimeError(f"Anthropic API error ({e.status_code}): {e.message}")

        for block in response.content:
            if block.type == "text":
                try:
                    architecture_response = ArchitectureResponse.model_validate_json(block.text)
                    return architecture_response
                except Exception as e:
                    raise RuntimeError(f"Failed to parse Anthropic response: {e}")

        raise RuntimeError("Anthropic returned an empty response.")