"""Replay the pre-audit metric function without changing production artifacts."""
import ast
from pathlib import Path
import subprocess
import sys

import pandas as pd

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from strategies import strategy_activation_scores as current
from strategies.strategy_mlp_scores import generate_signals
from tools.run_mlp_score_structure_experiment import _data_path, _load_winner

OUT = ROOT / 'results/mlp_measurement_audit_2026_09_21'


def main():
    # This file was clean at intake. Use the recorded immutable HEAD, not
    # today's movable branch, to recover its exact pre-audit definition.
    import json
    head = json.loads((OUT / 'input_manifest.json').read_text())['head']
    original = subprocess.check_output(['git', 'show', f'{head}:strategies/strategy_activation_scores.py'], text=True)
    tree = ast.parse(original)
    function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == 'calculate_metrics')
    namespace = dict(vars(current))
    exec(compile(ast.Module(body=[function], type_ignores=[]), '<recorded-pre-audit-metrics>', 'exec'), namespace)
    old = namespace['calculate_metrics']
    rows = []
    for tf in ['4H', '6H', '8H', '12H', '1D']:
        frame = pd.read_csv(_data_path('COINBASE_BTCUSD', tf))
        frame.columns = frame.columns.str.lower().str.strip()
        frame.time = pd.to_datetime(frame.time, unit='s' if pd.api.types.is_numeric_dtype(frame.time) else None, utc=True).dt.tz_localize(None)
        frame = frame.iloc[:-1].copy()
        params = _load_winner('COINBASE_BTCUSD', tf)
        params['_pine_time_start'] = '2017-12-01'
        signals = generate_signals(frame, **params)
        signals = signals[signals.time < '2026-03-01']
        before = old(signals, score_start='2017-12-01', min_trades=0)
        after = current.calculate_metrics(signals, score_start='2017-12-01', min_trades=0)
        rows.append({'tf': tf, **{f'old_{k}': v for k, v in before.items()}, **{f'new_{k}': v for k, v in after.items()}})
    result = pd.DataFrame(rows)
    result['old_calmar_rank_across_tf'] = result['old_Calmar Ratio'].rank(ascending=False)
    result['new_calmar_rank_across_tf'] = result['new_Calmar Ratio'].rank(ascending=False)
    result.to_csv(OUT / 'metric_version_comparison.csv', index=False)
    print(result[['tf', 'old_Calmar Ratio', 'new_Calmar Ratio', 'old_calmar_rank_across_tf', 'new_calmar_rank_across_tf']].to_string(index=False))


if __name__ == '__main__':
    main()
