# Copyright 2025, Seiko Epson Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the “Software”), to deal in
# the Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

import logging
import os

import pandas as pd

import epson_bdc.bdc_core
import epson_bdc.constants as CONSTANTS
from epson_bdc.bdc_core import calculate_bridge_deflection, output_error


def init_logger(exe_dir):
    """
    ロガーの初期化関数を定義
    """
    # このツール用のロガーを定義
    logger = logging.getLogger("epson_bdc")

    # 出力先に既にerror.logファイルが存在している場合、前の実行時のエラーと混在しないよう削除しておく
    error_log_file_path = os.path.join(exe_dir, "error.log")
    if os.path.exists(error_log_file_path):
        os.remove(error_log_file_path)

    # error.logの出力先がexeファイルと同階層になるようロガーに設定
    fh = logging.FileHandler(os.path.join(exe_dir, "error.log"), mode="a", delay=True)
    logger.addHandler(fh)


def main(lang):
    """
    メイン関数
    """
    # - EXE実行時のファイル探索の起点となる /_internal/epson_bdc ディレクトリのパスを取得
    epson_bdc_dir = os.path.dirname(epson_bdc.bdc_core.__file__)
    # - epson_bdc ディレクトリからさかのぼってexeファイルが存在するディレクトリのパスを取得
    exe_dir = os.path.dirname(os.path.dirname(epson_bdc_dir))

    # 日英対応表ファイルを読み込み lang に設定された言語の文言を読み込む
    df = pd.read_csv(
        os.path.join(epson_bdc_dir, "doc", "word_table.csv"), encoding="utf-8"
    )
    word_dict = {}
    # - 言語情報を word_dict 内に記録
    word_dict[CONSTANTS.KEY_LANG] = lang
    # - 文言を word_dict に格納
    for id, word in zip(df["ID"], df[lang], strict=True):
        word_dict[id] = word

    # プログラム中で発生するエラーをすべてキャッチする
    try:
        init_logger(exe_dir)

        calculate_bridge_deflection(exe_dir, epson_bdc_dir, word_dict)
    except Exception as e:
        # - キーの存在チェックは output_error 内で行う
        output_error(word_dict, CONSTANTS.KEY_UNEXPECTED_ERROR, e)
        return
