# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from ovos_workshop.skills.fallback import FallbackSkill
import sseclient
import requests
import json
import html
import re
from urllib.parse import quote_plus

class KagiSkill(FallbackSkill):

    def initialize(self):
        # compile replacement patterns
        self.pattern_ptag = re.compile(r'<[^>]*$')
        self.pattern_refs = re.compile(r'<div[^>]*>.*$', re.DOTALL)
        self.pattern_sups = re.compile(r'<sup[^>]*>.*?</sup>', re.DOTALL)
        self.pattern_tags = re.compile(r'<.*?>')
        self.pattern_brak = re.compile(r'【\d+】')

        self.register_fallback(self.handle_fallback_kagi, 80)

    def handle_fallback_kagi(self, message):
        self.verbose = self.settings.get("verbose", False)
        if "kagiSession" in self.settings:
            return self.get_using_session(message)
        elif "kagiApiKey" in self.settings:
            return self.get_using_api(message)
        else:
            self.log.error(
                "kagi not configured yet, please set kagiSession or kagiApiKey in %s",
                self.settings.path,
            )
            return False  # not configured yet

    def get_using_session(self, message):
        self.timeout = self.settings.get("timeout", 10)
        session_cookie = self.settings.get("kagiSession", "")
        header_content = {
            'Accept': 'text/event-stream',
            'cookie': f'kagi_session={session_cookie}'
        }
        read_url = f"https://kagi.com/stream_fastgpt?query={quote_plus(message.data.get('utterance'))}"
        try:
            client = sseclient.SSEClient(read_url,
                                         headers=header_content,
                                         timeout=(3, self.timeout))
            dirty_response = None
            for event in client:
                if self.verbose:
                    self.log.info(f'received data: {event.data}')
                if event.data == '"[DONE]"':
                    break
                dirty_response = event.data
            if dirty_response is None:
                self.log.error('bad session response from kagi')
                return False
            if self.verbose:
                self.log.info(f'using final payload: {dirty_response}')
            clean_response = self.clean_session_string(dirty_response)
            self.speak(clean_response)
            if self.verbose:
                self.log.info(f'cleaned up response: {clean_response}')
            return True
        except Exception as e:
            self.log.error(f'error fetching kagi session response: {str(e)}')
            return False
        finally:
            if client:
                try:
                    client.close()
                except:  # noqa: E722
                    pass

    def get_using_api(self, message):
        api_key = self.settings.get("kagiApiKey", "")
        header_content = {
            'Authorization': f'Bot {api_key}',
            'Content-type': 'application/json',
            'Accept': 'application/json'
        }
        js_data = json.dumps({'query': message.data.get('utterance')})
        read_url = 'https://kagi.com/api/v0/fastgpt'
        try:
            response = requests.post(read_url,
                                     data=js_data,
                                     headers=header_content,
                                     verify=False)
            if self.verbose:
                self.log.info(f'kagi api response: {response.text}')
            json_data = json.loads(response.text)
            dirty_response = self.get_api_response(json_data)
            if dirty_response is None:
                self.log.error('bad api response from kagi')
                return False
            if self.verbose:
                self.log.info(f'using response text: {dirty_response}')
            clean_response = self.clean_api_string(dirty_response)
            if self.verbose:
                self.log.info(f'cleaned up response: {clean_response}')
            self.speak(clean_response)
            return True
        except Exception as e:
            self.log.error(f'error fetching kagi api response: {str(e)}')
            return False

    def clean_session_string(self, raw_text):
        jsonstr = raw_text
        if not jsonstr.endswith('"'):
            # sometimes it bails before finishing the json string
            # if that happens let's fix it and read what we managed to get
            self.log.warn('got partial response from kagi, attempting to salvage')
            # clean up partial html if it got cut off mid-tag and add the closing quote
            jsonstr = re.sub(self.pattern_ptag, '', jsonstr) + '"'
        text = json.loads(jsonstr)
        text = re.sub(self.pattern_refs, '', text)
        text = re.sub(self.pattern_sups, '', text)
        text = re.sub(self.pattern_tags, '', text)
        return html.unescape(text)

    def clean_api_string(self, text):
        text = text.replace('*', '').replace('_', '')
        text = re.sub(self.pattern_brak, '', text)
        return text

    def get_api_response(self, json_data):
        if not isinstance(json_data.get("data"), dict):
            self.log.error("'data' missing from kagi api response")
            return None
        if "output" not in json_data["data"]:
            self.log.error("'output' missing from kagi api response")
            return None
        output_value = json_data["data"]["output"]
        if not isinstance(output_value, str):
            self.log.error(f"'output' was not a string in kagi api response (found {type(output_value).__name__})")
            return None
        return output_value