"""
概要:
    オリジナルのPython版tkfermiとC言語移植版を比較するベンチマークスクリプトです。
詳細説明:
    キャッシュを無効にしたPython版と、C言語に部分移植された高速版の間で、
    処理時間および計算結果の相対誤差を比較します。
    結果はコマンドラインに出力されるとともに、CSVファイルとして保存されます。
"""
import argparse
import csv
from pathlib import Path
import platform
import statistics
import sys
from time import perf_counter

import numpy as np
import scipy
import tkfermi_python as original
import tkfermi_c as native


def positive_int(text):
    """
    概要:
        文字列を1以上の正の整数に変換します。
    詳細説明:
        argparseの型変換用関数として使用されます。指定された文字列を整数に変換し、
        1未満であればエラーを発生させます。
    引数:
        :param text: 変換対象の文字列。
        :type text: str
    戻り値:
        :returns: 変換後の正の整数。
        :rtype: int
    例外:
        :raises argparse.ArgumentTypeError: 変換した値が1未満の場合に発生します。
    """
    value = int(text)
    if value < 1:
        raise argparse.ArgumentTypeError('must be >= 1')
    return value


def main():
    """
    概要:
        ベンチマークのメイン処理を実行します。
    詳細説明:
        コマンドライン引数を解析し、Python版とC言語版の各実装について指定された条件で
        実行時間を計測します。計算結果の相対誤差や高速化の度合いを計算し、
        標準出力への表示とCSVファイルへの保存を行います。
    """
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-n', '--count', type=positive_int, default=1000,
                        help='calls per eta per implementation per trial (default: 1000)')
    parser.add_argument('--repeat', type=positive_int, default=3)
    parser.add_argument('--eta', nargs='+', type=float,
                        default=[-10, -3, -1, -0.1001, -0.1, 0, 1, 5, 10, 19.9, 20, 50, 100])
    parser.add_argument('--order', type=float, choices=[0.5, 1.5], default=0.5)
    parser.add_argument('--output', type=Path, default=Path('tkfermi_comparison'))
    args = parser.parse_args()
    if not all(np.isfinite(x) for x in args.eta):
        parser.error('eta must be finite')

    # Replace the cached function in its own global namespace.
    cached = original._FermiIntegral_cached
    cached.cache_clear()
    original._FermiIntegral_cached = cached.__wrapped__
    assert not hasattr(original._FermiIntegral_cached, 'cache_info')
    print('Original cache: DISABLED (__wrapped__); C version: NO CACHE')
    print(f'{platform.platform()} | Python {sys.version.split()[0]} | '
          f'NumPy {np.__version__} | SciPy {scipy.__version__}')
    print(f'order={args.order}, count={args.count} per eta per trial, repeat={args.repeat}')
    # Identical one-argument wrapper overhead; real ctypes/LowLevelCallable overhead included.
    def python_fn(eta):
        return original.FermiIntegral_fast(eta, args.order)
    def c_fn(eta):
        return native.FermiIntegral_fast(eta, args.order)
    functions = [('Python', python_fn), ('C', c_fn)]
    rows, trials = [], []
    print(f'{"eta":>9} {"region":>12} {"Python us":>12} {"C us":>12} '
          f'{"speedup":>9} {"C/Py rel.diff":>15}')
    for eta in args.eta:
        py_value, c_value = python_fn(eta), c_fn(eta)  # warmup, untimed
        if not (np.isfinite(py_value) and np.isfinite(c_value)):
            raise RuntimeError(f'Nonfinite result at eta={eta}')
        difference = abs(c_value-py_value) / abs(py_value) if py_value else (
            0.0 if c_value == 0 else float('inf'))
        times = {'Python': [], 'C': []}
        for trial in range(args.repeat):
            for name, fn in functions[::1 if trial % 2 == 0 else -1]:
                start = perf_counter()
                for _ in range(args.count):
                    fn(eta)
                elapsed = perf_counter() - start
                times[name].append(elapsed)
                trials.append(dict(eta=eta, implementation=name, trial=trial+1,
                                   count=args.count, seconds=elapsed))
        py_time, c_time = (statistics.median(times[k]) for k in ('Python', 'C'))
        region = 'series' if eta < -0.1 else ('asymptotic' if eta >= 20 else 'quad')
        row = dict(eta=eta, order=args.order, region=region, count=args.count,
                   repeat=args.repeat, python_seconds=py_time, c_seconds=c_time,
                   python_us=py_time/args.count*1e6, c_us=c_time/args.count*1e6,
                   speedup=py_time/c_time, python_value=py_value,
                   c_value=c_value, relative_difference=difference)
        rows.append(row)
        print(f'{eta:9g} {region:>12} {row["python_us"]:12.3f} '
              f'{row["c_us"]:12.3f} {row["speedup"]:9.2f} {difference:15.3e}', flush=True)
    py_total = sum(row['python_seconds'] for row in rows)
    c_total = sum(row['c_seconds'] for row in rows)
    print(f'Sum of per-eta median times: Python={py_total:.6f}s, C={c_total:.6f}s; '
          f'speedup={py_total/c_total:.2f}x')
    print('relative_difference compares C with Python, NOT with an exact integral.')
    for suffix, data in [('summary', rows), ('trials', trials)]:
        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()