import json
import re

from openai import AsyncOpenAI

from app.utils.logger import get_logger
from config import apikey_settings
from app.utils.prompts.prompts import Prompt

# 로거 설정
logger = get_logger("chatgpt")

# fmt: on


class ChatgptService:
    """ChatGPT API 서비스 클래스

    GPT 5.0 모델을 사용하여 마케팅 가사 및 분석을 생성합니다.
    """

    def __init__(self):
        self.client = AsyncOpenAI(api_key=apikey_settings.CHATGPT_API_KEY)
        
    async def _call_structured_output_with_response_gpt_api(self, prompt: str, output_format : dict, model:str) -> dict:
        content = [{"type": "input_text", "text": prompt}]
        response = await self.client.responses.create(
            model=model, 
            input=[{"role": "user", "content": content}],
            text = output_format
        )
        structured_output = json.loads(response.output_text)
        return structured_output or {}

    async def generate_structured_output(
        self,
        prompt : Prompt,
        input_data : dict,
    ) -> str:
        prompt_text = prompt.build_prompt(input_data)

        print(f"[ChatgptService] Generated Prompt (length: {len(prompt_text)})")
        logger.info(f"[ChatgptService] Starting GPT request with structured output with model: {prompt.prompt_model}")

        # GPT API 호출
        response = await self._call_structured_output_with_response_gpt_api(prompt_text, prompt.prompt_output, prompt.prompt_model) 
        return response
