import os
import sys
import json
try:
    from dotenv import load_dotenv
except:
    print(f"\nImport error: dotenv")
    input("Install: pip install dotenv\n")
    exit()
try:
    import openai
    from openai import OpenAI
except:
    print(f"\nImport error: openai")
    input("Install: pip install openai\n")
    exit()


config_path = "translate.env"
input_path = "transcript.txt"
output_path = ""
guess_speakers = 1

max_bytes = 20000
max_tokens = 2000

if not os.path.isfile(config_path):
    script_dir = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(script_dir, config_path)

print()
# 環境変数読み込み
if os.path.isfile(config_path):
    print(f"config_path: {config_path}")
else:
    print(f"Warning: config_path {config_path} is not found")
load_dotenv(dotenv_path=config_path)

account_inf_path = os.getenv("account_inf_path", "accounts.env")
if os.path.isfile(account_inf_path):
    print(f"account_inf_path: {account_inf_path}")
else:
    print(f"Warning: account_inf_path {account_inf_path} is not found")
load_dotenv(dotenv_path=account_inf_path)

# APIキー設定
api_key = os.getenv("OPENAI_API_KEY")
if api_key is None or api_key == "":
    print(f"Error: api_key is not found.")
    exit()
else:
    print(f"api_key: {api_key}")


client = OpenAI(api_key=api_key)

openai_model = os.getenv("openai_model", "gpt-4o")
temperature = float(os.getenv("temperature", "0.3"))
max_tokens = int(os.getenv("max_tokens", max_tokens))

print(f"openai_model : {openai_model}")


argv = sys.argv
nargs = len(argv)
if nargs > 1: input_path = argv[1]
if nargs > 2: output_path = argv[2]
if nargs > 3: max_bytes = int(argv[3])

print(f"input_path : {input_path}")
print(f"output_path: {output_path}")
print(f"openai_model: {openai_model}")
print(f"temperature : {temperature}")
print(f"max_tokens  : {max_tokens}")
print(f"max_bytes   : {max_bytes}")


prompt = "あなたは大学で半導体を研究している教授です。以下の講義の文字起こしを要約してください。"


def summarize_text(text: str) -> str:
    print("文字起こしテキストを要約中...")
    response = client.chat.completions.create(
        model=openai_model,
        messages=[
            {"role": "system", "content": prompt},
            {"role": "user", "content": text}
        ],
        temperature=temperature,
        max_tokens=max_tokens
    )
    return response.choices[0].message.content.strip()

def save_text_to_file(filename: str, content: str):
    try:
        with open(filename, "w", encoding="utf-8") as f:
            f.write(content)
        print(f"'{filename}' に内容を保存しました。")
    except IOError as e:
        print(f"ファイルの保存中にエラーが発生しました: {e}")

def main():
    global output_path
    
    output_dir = os.path.dirname(os.path.abspath(input_path)) or "."
    file_body = os.path.splitext(os.path.basename(input_path))[0]

    if os.path.exists(input_path):
        with open(input_path, "r", encoding="utf-8") as f:
            text = f.read()
    else:
        print(f"\nError: Could not read [{input_path}]\n")
        exit()

    if output_path == "":
        output_path = os.path.join(output_dir, f"{file_body}_output.txt")    

    summary = summarize_text(text[:max_bytes])
    save_text_to_file(output_path, summary)

    print("\n===== 要約結果 =====\n")
    print(summary)
    
    input("\nPress ENTER to terminate>>\n")


if __name__ == "__main__":
    main()
