from fastapi import APIRouter, HTTPException, Request, Depends
from fastapi.responses import RedirectResponse
import openai
import boto3
import os
import time
from schemas import ChatMessage, SpeechText, QuizMessage, LineUser, MedicineText, UserQuestion
from config import logger
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
import logging
import requests
from bs4 import BeautifulSoup
import numpy as np
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from urllib.parse import urljoin, urlparse
import time
import ast
from google import genai
from google.genai import types

router = APIRouter()


API_KEY = "AIzaSyB0gBfm2dXJaxUoX-T40SDomM7f4vQkQQU"
client = genai.Client(api_key=API_KEY)

s3_client = boto3.client('s3')
bucket_name = 'shanri-ai-chatbot-for-text-to-speech'


async def ask_openai(messages):
    valid_messages = [msg for msg in messages if msg.get('content')]
    response = openai.chat.completions.create(
        model="gpt-4o",
        messages=valid_messages
    )
    answer = response.choices[0].message.content.strip()
    return answer


async def synthesize_speech(text, user_id):
    response = client.audio.speech.create(
        model="tts-1",
        voice="nova",
        input=text,
    )
    audio_file = f"tmp/audio-{user_id}-{time.time()}.mp3"
    with open(audio_file, 'wb') as f:
        for chunk in response.iter_bytes():
            f.write(chunk)
    s3_key = f"{user_id}-{time.time()}.mp3"
    s3_client.upload_file(audio_file, bucket_name, s3_key)
    os.remove(audio_file)
    return f"https://{bucket_name}.s3.amazonaws.com/{s3_key}"


# # ✅ 특정 웹사이트(ug-inc.net) 크롤링 함수
# async def fetch_website_data(url):
#     """특정 URL에서 정보를 가져옴"""
#     try:
#         headers = {"User-Agent": "Mozilla/5.0"}
#         response = requests.get(url, headers=headers, timeout=10)
#         response.raise_for_status()

#         soup = BeautifulSoup(response.text, "html.parser")
#         paragraphs = soup.find_all("p")
#         text = "\n".join([p.get_text() for p in paragraphs])
#         return text
#     except requests.RequestException as e:
#         print(f"웹사이트 정보 가져오기 실패: {e}")
#         return ""

# ✅ 특정 웹사이트(segue-g) 크롤링 함수
def init_driver():
    options = Options()
    options.add_argument("--headless")
    options.add_argument("--disable-gpu")
    options.add_argument("--no-sandbox")
    return webdriver.Chrome(options=options)

def is_same_domain(base_url, test_url):
    return urlparse(base_url).netloc == urlparse(test_url).netloc

async def fetch_all_pages_with_selenium(url_list):
    """url_list에 있는 각 페이지의 sections_group HTML만 크롤링 (내부 링크 X)"""
    driver = init_driver()
    all_html = ""

    try:
        for url in url_list:
            try:
                print(f"\n🟢 크롤링 중: {url}")
                driver.get(url)
                time.sleep(2)
                soup = BeautifulSoup(driver.page_source, "html.parser")

                # ✅ sections_group 클래스를 가진 요소만 가져오기
                sections = soup.find_all(class_="sections_group")

                page_html = ""
                for section in sections:
                    page_html += section.prettify()  # ✅ HTML 코드로 가져오기

                all_html += f"<!-- {url} -->\n{page_html}\n\n"

            except Exception as e:
                print(f"[에러] {url}: {e}")

        return all_html
    finally:
        driver.quit()
    return all_text

# # ✅ 질문과 관련 있는 텍스트 추출 함수
# async def find_relevant_text(question, text_data, max_sentences=100, max_length=10000):
#     """질문과 관련 있는 텍스트를 상위 20개 문장으로 제한"""
#     sentences = text_data.split("\n")
#     vectorizer = TfidfVectorizer().fit_transform([question] + sentences)
#     similarities = (vectorizer * vectorizer.T).toarray()[0][1:]

#     # 유사도가 높은 문장 정렬 후 상위 max_sentences 개만 선택
#     top_indices = np.argsort(similarities)[-max_sentences:]
#     top_sentences = [sentences[i] for i in top_indices]
#     return "\n".join(top_sentences)[:max_length]


# ✅ gemini를 사용해 생성된 답변을 더 자연스럽고 정돈되게 수정 + 마크다운형식
def refine_answer_with_gemini(raw_answer):
    prompt = f"""
    以下の内容を丁寧に修正してください。

    - 企業名の代わりに「弊社」という表現を使ってください。
    - 本社のスタッフがお客様に話しかける感じにしてください。
    - 「ホームページに記載されている」といった表現は削除してください。
    - 数値がある場合は、マークダウン形式の表で表示してください。
    - 冒頭の挨拶文（例：「お客様各位」「いつもご利用ありがとうございます」「お問い合わせありがとうございます」など）は省略してください。

    以下が修正対象の文章です：
    {raw_answer}
    """

    response = client.models.generate_content(
        model="gemini-1.5-pro",
        contents=prompt,
        config=types.GenerateContentConfig(
            response_modalities=["TEXT"]
        )
    )

    return response.text

async def choose_homepage_url(question):
    """homepage_urlを選択する関数"""

    # プロンプト全体を一つの文字列に構成
    prompt = """
    以下の情報を元に、質問に対して最も適切なURLを一つ以上配列の形で選んでください。

    - 出力形式は配列のみを返すこと。例: ['https://segue-g.jp/company/boardmember/index.html','https://segue-g.jp/ir/results/settle.html']
    - 回答や説明文は不要です。配列形式のみ出力してください。

    【URLリスト】
    - 企業理念 : https://segue-g.jp/company/sdgs/index.html
    - IR 情報 : https://segue-g.jp/ir/index.html
    - 財務、業績報告 : https://segue-g.jp/ir/results/settle.html
    - 株式情報 : https://segue-g.jp/ir/stock/index.html
    - 当社の強み : https://segue-g.jp/ir/investor/strong_point/index.html
    - 成長戦略 : https://segue-g.jp/ir/investor/strategy/index.html
    - 会社概要 : https://segue-g.jp/company/basic/index.html
    - 企業理念 : https://segue-g.jp/company/brand/index.html
    - 沿革 : https://segue-g.jp/company/history/index.html
    - 役員一覧 : https://segue-g.jp/company/boardmember/index.html
    - 事業紹介 : https://segue-g.jp/business/index.html

    【質問】
    """ + question

    response = client.models.generate_content(
        model="gemini-1.5-pro",
        contents=prompt,
        config=types.GenerateContentConfig(
            response_modalities=["TEXT"]
        )
    )
    return response.text.strip()

async def generate_gemini_answer(question):
    # 질문에 "御社の"가 없으면 추가
    if not question.startswith("御社の"):
        question = "御社の" + question

    # 웹사이트를 크롤링 후 관련된 문장을 추출한다.
    url_list_str = await choose_homepage_url(question)
    url_list = ast.literal_eval(url_list_str)

    website_data = await fetch_all_pages_with_selenium(url_list)

    print("segue-g 사이트 크롤링 결과: " + website_data)

    print("url_list : " + str(url_list))

    #print(website_data)
    # relevant_text = await find_relevant_text(question, website_data) if website_data else ""

    # print("segue-g 사이트 크롤링 결과: " + relevant_text)

    # 웹사이트 질문
    websearch_input = "株式会社 セグエグループ " + question

    # gemini 가 질문에 관련된 내용을 검색한다.
    websearch_data = client.models.generate_content(
        model="gemini-1.5-pro",
        contents=[websearch_input],
        config=types.GenerateContentConfig(
            tools=[types.Tool(google_search_retrieval=types.GoogleSearchRetrieval())],
            response_modalities=["TEXT"]
        )
    )

    print("웹 검색결과: " + websearch_data.text)

    prompt_parts = [
        "※ 回答には情報源のリンクや「ホームページに記載されている」などの表現を含めないでください。"
        "※ 回答は丁寧である必要はありますが、挨拶文（例：「お客様各位」「お問い合わせありがとうございます」など）は含めず、要点から始めてください。"
        "※ 回答を生成するときに、企業公式サイトの情報とウェブ検索の情報が同じ情報を持っている場合は、それを参照してください。"
        "※ 情報の内容が異なる場合は、企業公式サイトの情報を優先してください。"
    ]

    if website_data:
        prompt_parts.append(f"[企業公式サイトの情報]:\n{website_data}")

    if websearch_data:
        prompt_parts.append(f"[ウェブ検索の情報]:\n{websearch_data.text}")

    prompt_parts.append(f"[質問]:\n{question}")

    full_prompt = "\n\n".join(prompt_parts)

    response = client.models.generate_content(
        model="gemini-1.5-pro",
        contents=full_prompt,
        config=types.GenerateContentConfig(
            response_modalities=["TEXT"]
        )
    )

    refined_answer = refine_answer_with_gemini(response.text)

    return refined_answer


@router.get("/health")
async def health_check():
    return {"status": "healthy"}


@router.post("/apigeV2_2/speech")
async def speech(speech_text: SpeechText):
    text = speech_text.text
    chat_token = speech_text.chat_token
    if not text:
        raise HTTPException(status_code=400, detail="Text is required")
    audio_file = await synthesize_speech(text, chat_token)
    return {"audio_file": audio_file}


# 질문을 받아서 처리하는 gemini API
@router.post('/apigeV2_2/ask_question')
async def gemini_question(user_question: UserQuestion):
    question_text = user_question.question.strip()
    if not question_text:
        raise HTTPException(status_code=400, detail="Question is required")

    generated_answer = await generate_gemini_answer(question_text)
    return {"answer": generated_answer}

