"""添付6実装のF_{1/2}(eta)を比較する。元のプログラムは変更しない。"""
import argparse
import csv
import importlib.util
import math
from pathlib import Path
import statistics
import sys
from time import perf_counter

import numpy as np
from scipy.integrate import quad
from scipy.special import expit


SOURCES = [
    ('sonnet5.5', 'Ne-T_sonnet5.5.py'),
    ('tkfermi', 'tkfermi_integral.py'),
    ('copilot', 'Ne-T_copilot.py'),
    ('Gemini3.8Flash', 'Ne-T_Gemini3.8Flash.py'),
    ('Gemini3Flash', 'Ne-T_Gemini3Flash.py'),
    ('sol', 'Ne-T_sol.py'),
]
NORMALIZATION = math.gamma(1.5)


def load_function(label, path):
    # ファイル名にハイフンや括弧が含まれるので、パスからimportする。
    name = 'fd_bench_' + label.replace('.', '_')
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module  # dataclassを使用するモジュールにも必要
    spec.loader.exec_module(module)

    disabled = []
    for name, obj in list(vars(module).items()):
        if callable(obj) and hasattr(obj, 'cache_clear') and hasattr(obj, '__wrapped__'):
            obj.cache_clear()
            # キャッシュのラッパーを外す。毎回cache_clearする時間は計測しない。
            while hasattr(obj, '__wrapped__'):
                obj = obj.__wrapped__
            setattr(module, name, obj)
            disabled.append(name)

    # 全実装を 1/Gamma(3/2) * integral(x**0.5 * f, x=0..inf) に統一。
    if label == 'tkfermi':
        fn = module.FermiIntegral_half
        function = lambda eta: fn(eta) / NORMALIZATION
    elif label == 'sonnet5.5':
        function = module.fd_half
    elif label == 'Gemini3Flash':
        fn = module.Fj
        function = lambda eta: fn(eta) / NORMALIZATION
    elif label == 'sol':
        function = module.Fj
    else:
        fn = module.Fj
        function = lambda eta: fn(0.5, eta)
    return function, disabled


def reference(eta):
    # 精度確認用の独立な数値積分。ベンチマーク時間には含めない。
    # 負のetaではexp(eta)を外に出して小さな値の相対精度を保つ。
    scale = math.exp(eta) if eta < 0 else 1.0
    def integrand(t):
        x = t * t
        f = math.exp(-x) * expit(x - eta) if eta < 0 else expit(eta - x)
        return 2 * t * t * f
    cuts = sorted(set([0.0, math.sqrt(max(eta, 0)),
                       math.sqrt(max(eta, 0) + 100)]))
    value = sum(quad(integrand, a, b, epsabs=1e-12, epsrel=1e-12,
                     limit=500)[0] for a, b in zip(cuts[:-1], cuts[1:]))
    return scale * value / NORMALIZATION


def positive_int(text):
    value = int(text)
    if value < 1:
        raise argparse.ArgumentTypeError('1以上を指定してください')
    return value


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-n', '--count', type=positive_int, default=1000,
                        help='各実装・各試行の総計算回数 (default: 1000)')
    parser.add_argument('--repeat', type=positive_int, default=3,
                        help='試行数。代表値は中央値 (default: 3)')
    parser.add_argument('--eta', type=float, nargs='+',
                        default=[-10, -3, -1, -0.1, 0, 1, 5, 19.9, 20, 50, 100],
                        help='順番に循環させるetaのリスト')
    parser.add_argument('--source-dir', type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument('--output', type=Path, default=Path('benchmark_fd'))
    args = parser.parse_args()
    if not all(math.isfinite(e) for e in args.eta):
        parser.error('etaは有限値を指定してください')
    if args.count < len(args.eta):
        parser.error('countはetaの個数以上にしてください')
    # 全実装で同じ入力・順序。入力配列の作成とimportは計測外。
    inputs = [args.eta[i % len(args.eta)] for i in range(args.count)]
    functions = []
    for label, filename in SOURCES:
        fn, disabled = load_function(label, args.source_dir / filename)
        functions.append((label, fn))
        print(f'{label}: cache disabled: {", ".join(disabled) or "none found"}')

    # ウォームアップ兼精度確認。例外や積分警告を隠さない。
    accuracy = []
    errors = {}
    refs = [reference(eta) for eta in args.eta]
    for label, fn in functions:
        errors[label] = []
        for eta, ref in zip(args.eta, refs):
            value = float(fn(eta))
            relative = abs(value - ref) / abs(ref) if ref != 0 else float('nan')
            if not math.isfinite(value):
                relative = float('inf')
            errors[label].append(relative)
            accuracy.append(dict(implementation=label, eta=eta, value=value,
                                 reference=ref, relative_error=relative))

    times = {label: [] for label, _ in functions}
    # 試行ごとに実行順を回転して、常に同じ実装が先頭になるのを避ける。
    for trial in range(args.repeat):
        offset = trial % len(functions)
        for label, fn in functions[offset:] + functions[:offset]:
            start = perf_counter()
            for eta in inputs:
                fn(eta)
            elapsed = perf_counter() - start
            times[label].append(elapsed)
            print(f'trial {trial+1}/{args.repeat}: {label:16s} {elapsed:.6f} s', flush=True)

    rows = []
    for label, _ in functions:
        seconds = statistics.median(times[label])
        rows.append(dict(implementation=label, count=args.count, repeat=args.repeat,
                         median_seconds=seconds, min_seconds=min(times[label]),
                         us_per_call=seconds / args.count * 1e6,
                         max_relative_error=max(errors[label])))
    rows.sort(key=lambda row: row['median_seconds'])
    print('\nNormalized F_1/2; count = calls per implementation per trial')
    print(f'{"implementation":16s} {"median(s)":>12s} {"us/call":>12s} {"max rel.err":>14s}')
    for row in rows:
        print(f'{row["implementation"]:16s} {row["median_seconds"]:12.6f} '
              f'{row["us_per_call"]:12.3f} {row["max_relative_error"]:14.3e}')
    for suffix, data in [('timing', rows), ('values', accuracy),
                         ('trials', [dict(implementation=k, trial=i+1, seconds=t)
                                     for k, ts in times.items() for i, t in enumerate(ts)])]:
        path = args.output.with_name(args.output.name + '_' + suffix + '.csv')
        path.parent.mkdir(parents=True, exist_ok=True)
        with path.open('w', newline='', encoding='utf-8-sig') as f:
            writer = csv.DictWriter(f, fieldnames=list(data[0]))
            writer.writeheader()
            writer.writerows(data)
        print('Saved:', path)


if __name__ == '__main__':
    main()
