#!/usr/bin/env python3
import os
import json
from pathlib import Path

def load_params_tree(base_path="user_data/strategies/params/"):
    base = Path(base_path)
    params_tree = {}
    if not base.exists():
        raise FileNotFoundError(f"Base path '{base_path}' not found.")

    for pair_dir in base.iterdir():
        if not pair_dir.is_dir():
            continue
        pair = pair_dir.name  # ex : BTC-USDT
        params_tree.setdefault(pair, {})

        for trend_dir in pair_dir.iterdir():
            if not trend_dir.is_dir():
                continue
            trend = trend_dir.name  # ex : bull / bear / range
            params_tree[pair].setdefault(trend, [])

            for file in trend_dir.glob("*-hyperopt_result.json"):
                filename = file.name

                # Extraire START et END
                try:
                    prefix = filename.replace("-hyperopt_result.json", "")
                    start, end = prefix.split("-", 1)  # split en 2
                except Exception:
                    start = None
                    end = None

                # Lire le JSON
                try:
                    with open(file, "r") as f:
                        content = json.load(f)
                except Exception as err:
                    content = {"error": str(err)}

                params_tree[pair][trend].append({
                    "start": start,
                    "end": end,
                    "file": str(file),
                    "content": content,
                })

    return params_tree

def getTrend(data, pair, trend, space, param):
    return data[pair][trend][0]['content']['params'][space][param]


if __name__ == "__main__":
    data = load_params_tree("user_data/strategies/params/")
    # print(data)
    # Test affichage minimal
    for pair, trends in data.items():
        for trend, entries in trends.items():
            if entries:
                indic_5m = getTrend(data, pair, trend, 'buy', 'indic_5m')
                indic_deriv1_5m = getTrend(data, pair, trend, 'buy', 'indic_deriv1_5m')
                indic_deriv2_5m = getTrend(data, pair, trend, 'buy', 'indic_deriv2_5m')

                indic_5m_sell = getTrend(data, pair, trend, 'sell', 'indic_5m_sell')
                indic_deriv1_5m_sell = getTrend(data, pair, trend, 'sell', 'indic_deriv1_5m_sell')
                indic_deriv2_5m_sell = getTrend(data, pair, trend, 'sell', 'indic_deriv2_5m_sell')

                print(f"{pair} -> {trend} -> {indic_5m} {indic_deriv1_5m} {indic_deriv2_5m} {indic_5m_sell} {indic_deriv1_5m_sell} {indic_deriv2_5m_sell}")
                # for entry in entries:
                #     print(entry)
