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


class OpenAIProvider(LLMProvider):
    def __init__(self, api_key: str, model: str):
        try:
            import openai
        except ImportError:
            raise ImportError('OpenAI provider requires the openai package. Install with: pip install "archo[openai]"')

        self.api_key = api_key
        self._openai_sdk = openai
        self.client = openai.OpenAI(api_key=self.api_key)
        self.model = model

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

        try:
            response = self.client.chat.completions.parse(
                model=self.model,
                max_completion_tokens=4096,
                messages=[
                    {"role": "system", "content": SYSTEM_PROMPT},
                    {"role": "user", "content": file_bundle},
                ],
                response_format=ArchitectureResponse,
            )
        except self._openai_sdk.AuthenticationError:
            raise RuntimeError("Invalid API key — check LLM_API_KEY.")
        except self._openai_sdk.APIConnectionError:
            raise RuntimeError("Could not connect to OpenAI API — check your network.")
        except self._openai_sdk.APIStatusError as e:
            raise RuntimeError(f"OpenAI API error ({e.status_code}): {str(e)}")

        if not response.choices:
            raise RuntimeError("OpenAI returned an empty response.")

        return response.choices[0].message.parsed