import { Injectable, Logger } from "@nestjs/common";
import ResponseDto from "../../dto/response.dto";
import { OllamaAskDto } from "../../dto/ollama.dto";

@Injectable()
export default class OllamaProvider {

    private logger: Logger = new Logger(OllamaProvider.name);
    private url: string    = "http://localhost:11434";

    /**
     * Check if has ollama installed
     */
    async hasAIInstalled(): Promise<ResponseDto>{

        const response: ResponseDto = new ResponseDto();

        try{

            const responseOllama = 
                await fetch(
                    this.url
                );

            if(responseOllama.status == 200){
                response.success = true;
            }

        }catch(e: any){
            this.logger.log(e.message);
        }

        return response;
    }

    /**
     * Ask to ollama gpt-oss:120b-cloud model
     * @param payload 
     * @returns 
     */
    async ask(payload: OllamaAskDto): Promise<ResponseDto>{

        const response: ResponseDto = new ResponseDto();

        try{

            const responseOllama = 
                await fetch(
                    `${this.url}/api/generate`,
                    {
                        method: "POST",
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(
                            {
                                "model" : "gpt-oss:120b-cloud",
                                "prompt": payload.question,
                                "stream": false
                            }
                        )
                    }
                );

            if(responseOllama.status == 200){

                const json = await responseOllama.json();
                if(json && json.response){
                    response.success = true;
                    response.data    = {"aiResponse": json.response};
                }

            }

        }catch(e: any){
            this.logger.log(e.message);
        }

        return response;
    }

}