from fastapi import HTTPException
from pydantic import BaseModel
from typing import Optional
from enum import Enum
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from core import ResponseStatus
from schemas import WebhookResponse
from services.response_manager import ResponseManager
from services.audio_service import AudioService

class WebhookService:
    def __init__(self, response_manager: ResponseManager, audio_service: AudioService):
        self.response_manager = response_manager
        self.audio_service = audio_service

    def process_webhook_response(self, response: WebhookResponse) -> dict:
        print("Received webhook data from n8n:", response.dict())
        
        if response.agent_responded == 'yes' and response.agent_response:
            if response.filename:
                audio_file_path = self.audio_service.get_audio_file(response.filename)
                self.response_manager.store_response(response.agent_response, audio_file_path)
                print("Agent response stored successfully.")
            else:
                self.response_manager.store_response(response.agent_response)
                print("Agent text response stored successfully.")
        
        return {"status": ResponseStatus.SUCCESS, "message": "Webhook received and processed successfully."}

