from __future__ import annotations

import argparse
from pathlib import Path

from ..core.config import load_config
from ..domain.calculator import PayrollCalculator
from ..io.exporter import export_payroll_results
from ..io.parser import MonthlySummaryParser


DEFAULT_OUTPUT = Path("outputs/payroll_result.xlsx")
DEFAULT_INPUT = Path(
    "/Users/jiaolongyan/Library/Containers/com.tencent.xinWeChat/Data/Documents/"
    "xwechat_files/wxid_iy9g88794bjh22_e458/msg/file/2026-06/"
    "宁波兆安流体科技有限公司_月度汇总_20260501-20260531.xlsx"
)


def build_parser() -> argparse.ArgumentParser:
    """命令行入口保留给本地批处理 Excel，不参与 Web API。"""
    parser = argparse.ArgumentParser(description="根据月度考勤汇总 Excel 计算工资和考勤扣款。")
    parser.add_argument(
        "input",
        nargs="?",
        help="月度汇总 Excel 路径；不传时默认使用本次提供的 2026-05 月度汇总表",
    )
    parser.add_argument(
        "-c",
        "--config",
        help="工资规则 JSON。未提供时使用内置规则；示例见 config/salary_rules.example.json",
    )
    parser.add_argument(
        "-o",
        "--output",
        default=str(DEFAULT_OUTPUT),
        help=f"输出 Excel 路径，默认：{DEFAULT_OUTPUT}",
    )
    return parser


def main() -> None:
    """直接运行脚本时生成一份工资 Excel。"""
    args = build_parser().parse_args()
    config = load_config(args.config)
    input_path = Path(args.input) if args.input else DEFAULT_INPUT
    if not input_path.exists():
        raise FileNotFoundError(
            f"未找到输入 Excel：{input_path}\n"
            "请在运行参数里传入月度汇总 Excel 路径，例如：python main.py /path/to/月度汇总.xlsx"
        )

    parser = MonthlySummaryParser(config.attendance)
    employees = parser.parse(input_path)

    calculator = PayrollCalculator(config)
    results = calculator.calculate(employees)

    output_path = export_payroll_results(results, config, args.output)
    print(f"已生成工资计算结果：{output_path.resolve()}")
    print(f"员工数：{len(results)}")
