import speech_recognition as sr
import requests
import json
import pandas as pd
from google.cloud import texttospeech
import playsound
import datetime

# 카카오 API 관련 변수
kakao_speech_url = "https://kakaoi-newtone-openapi.kakao.com/v1/recognize"
kakao_synthsize_url = "https://kakaoi-newtone-openapi.kakao.com/v1/synthesize"
kakao_api_key = '카카오 api 키'
recog_headers = {
    "Content-Type": "application/octet-stream",
    "X-DSS-Service": "DICTATION",
    "Authorization": "KakaoAK " + kakao_api_key
    }

# 기상청 동네예보 API 관련 변수
weather_url = "http://apis.data.go.kr/1360000/VilageFcstInfoService/getVilageFcst"
weather_api_key = "기상청 api 키"


def voice_recognition():
    '''1. 마이크에서 소리를 입력받음.'''
    r = sr.Recognizer()
    with sr.Microphone(sample_rate=16000) as source:
        r.adjust_for_ambient_noise(source)
        print("마이크가 활성화되었습니다.")
        audio = r.listen(source, timeout=4)
    return audio


def kakao_api(audio):
    '''2. 카카오 음성 API를 활용하여 소리를 텍스트로 전환'''
    res = requests.post(kakao_speech_url, headers=recog_headers, data=audio.get_raw_data())
    result_json_string = res.text[res.text.index('{"type":"finalResult"'):res.text.rindex('}')+1]
    result = json.loads(result_json_string)
    print("나 :"+ result['value'])
    return result['value']


def get_keyword(question):
    '''3. 질문에서 날짜와 질문 주제를 뽑음'''
    dates = ["오늘", "내일", "지금"]
    q_date = "오늘"
    q_main = ""

    for date in dates:
        if date in question:
            q_date = date

    if "영실" in question:
        q_main = "영실"
    elif "운세" in question:
        q_main = "날씨"
    elif "날씨" in question:
        q_main = "운세"
    elif "시리" in question:
        q_main = "시리"
    else:
        q_main = "식별불가"

    return q_main, q_date


def weather_api(date):
    '''4. 쿼리에 날짜정보를 담아 기상청에 요청(지역 : 대전 유성구 온천1동)'''
    # 오늘, 예측날짜 변수설정
    now_date = str(datetime.datetime.now()).split(" ")[0]
    today = ''.join(now_date.split("-"))
    target_day = today
    if date == "내일":
        target_day = str(int(today)+1)

    #쿼리에 기준시간/날짜 설정 후 기상청 API에 requests
    queryParams = '?' + \
                  'serviceKey=' + weather_api_key+ \
                  '&numOfRows='+ '9999' + \
                  '&pageNo='+ '1' + \
                  '&base_date='+ today + \
                  '&base_time='+ "0200" + \
                  '&dataType='+ 'JSON' + \
                  '&nx='+ '66' + \
                  '&ny='+ '101'
    res = requests.get(weather_url + queryParams)
    js = json.loads(res.content)

    return js, target_day


def weather_convert(js, target_day):
    '''5. 기상청에서 받아온 날씨정보를 보다 편한 활용을 할 수 있도록 dictionary로 만들어줌.'''

    # JSON형태의 날씨정보 받아 dataframe으로 변환, 필요한 데이터만 확보
    weather_df = pd.DataFrame(js['response']['body']['items']['item'])
    weather_df = weather_df[(weather_df['fcstTime']=='0900') & (weather_df['fcstDate']==target_day)]
    weather_df = weather_df[weather_df['category'].isin(['T3H', 'PTY', 'SKY', 'WSD'])]
    weather_df = weather_df[['category', 'fcstValue']]

    # [SKY: 구름상태]와 [PTY: 강수형태]는 카테고리변수, 미리 엑셀에 정리해뒀으므로 merge
    df = pd.read_csv('weather_info.csv', encoding='CP949')
    df['fcstValue'] = df['fcstValue'].astype(str)
    weather_df = pd.merge(weather_df, df, on = ['category', 'fcstValue'], how='left')

    # [WSD: 풍속]과 [T3H: 평균 기온]은 numeric 변수, 사전으로 치환하여 범주에 따라 텍스트 설정
    weather_dict = weather_df.set_index('category').to_dict()
    if float(weather_dict['fcstValue']["WSD"]) < 3:
        weather_dict['value']["WSD"] = "바람 한 점 없이 "
    elif float(weather_dict['fcstValue']["WSD"]) > 20:
        weather_dict['value']["WSD"] = "강한 바람이 불며 "
    else:
        weather_dict['value']["WSD"] = ""

    if int(weather_dict['fcstValue']["T3H"]) < 0:
        weather_dict['value']["T3H"] = "기온은 영하" + weather_dict['fcstValue']["T3H"][1:] + "도 이며 "
    else:
        weather_dict['value']["T3H"] = "기온은" + weather_dict['fcstValue']["T3H"] + "도 이며 "

    return weather_dict['value']


def match_answer(main, date):
    '''6. 질문 주제와 날짜에 맞춰 대답을 생성'''
    base_ans = date + "의 " + main + "는 다음과 같습니다."
    if main == "날씨":
        js, target_day = weather_api(q_date)
        weather_dict = weather_convert(js, target_day)
        add_ans = (
            weather_dict['WSD'] +
            weather_dict['SKY'] +
            weather_dict['T3H'] +
            weather_dict['PTY']
            )
        answer = base_ans+add_ans

    elif main == "운세":
        add_ans = "오늘은 운명의 신이 당신의 잔잔한 일상에 미풍을 불어오는 날입니다. 과거에 스쳤던 인연을 뜻밖의 장소에서 다시 만날 수 있습니다"
        answer = base_ans+add_ans

    elif main == "영실":
        answer = "네 지평님 말씀하세요."

    elif main == "시리":
        answer = "저는 시리가 아니에요."

    else:
        answer = "잘 못알아들었어요."
    return answer


def make_voice(answer):
    '''7. 생성된 대답을 google api를 사용하여 음성으로 변환'''
    client = texttospeech.TextToSpeechClient()
    input_text = texttospeech.SynthesisInput(text=answer)
    # Note: the voice can also be specified by name.
    # Names of voices can be retrieved with client.list_voices().
    voice = texttospeech.VoiceSelectionParams(
        language_code="ko-KR",
        name="ko-KR-Wavenet-A",
        ssml_gender=texttospeech.SsmlVoiceGender.MALE,
    )

    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.MP3
    )

    response = client.synthesize_speech(
        request={"input": input_text, "voice": voice, "audio_config": audio_config}
    )

    with open("output.mp3", "wb") as out:
        out.write(response.audio_content)
    print("영실: "+answer)
    playsound.playsound("output.mp3")


if __name__ == "__main__":
    while True:
        audio = voice_recognition()
        try:
            question = kakao_api(audio)
            q_main, q_date = get_keyword(question)
            answer = match_answer(q_main, q_date)
            make_voice(answer)
        except:
            print("no ask")
