"""Generate Jesse strategy files from VARRD-validated hypotheses."""

from __future__ import annotations

import re
from pathlib import Path

from jinja2 import Environment, FileSystemLoader

from varrd.models import HypothesisDetail

from varrd.jesse.translator import (
    atr_to_jesse_sl,
    atr_to_jesse_tp,
    varrd_market_to_jesse_pair,
    varrd_timeframe_to_jesse,
    varrd_to_jesse_entry,
    varrd_to_jesse_indicators,
)

_TEMPLATE_DIR = Path(__file__).parent / "templates"


def _sanitize_class_name(name: str, max_words: int = 4) -> str:
    """Convert hypothesis name to a valid Python class name.

    'RSI oversold reversal on BTC' -> 'VARRDRsiOversoldReversal'
    """
    cleaned = re.sub(r"[^a-zA-Z0-9 ]", "", name)
    parts = cleaned.split()[:max_words]
    class_name = "".join(word.capitalize() for word in parts)
    if not class_name:
        class_name = "Strategy"
    return f"VARRD{class_name}"


def _comment_wrap(text: str) -> str:
    """Wrap multi-line text so every line is a Python comment."""
    lines = text.strip().splitlines()
    return "\n".join(f"# {line.rstrip()}" for line in lines)


def generate_strategy(
    hypothesis: HypothesisDetail,
    strategy_name: str | None = None,
    exchange: str = "Binance Futures",
    setup_code: str = "",
    risk_percent: float = 1.0,
) -> tuple[str, str]:
    """Generate a Jesse strategy file from a VARRD hypothesis.

    Args:
        hypothesis: HypothesisDetail from the varrd SDK.
        strategy_name: Override for the strategy class name.
        exchange: Jesse exchange name (default: Binance Futures).
        setup_code: VARRD setup_code if not on the hypothesis object.
        risk_percent: Risk per trade as % of balance (default: 1.0).

    Returns:
        (strategy_py_content, routes_py_content) — the strategy .py file
        content and a matching routes.py file content.
    """
    # --- Resolve fields ---
    market = hypothesis.market or ""
    direction = (hypothesis.direction or "LONG").upper()
    formula = hypothesis.formula or "True"
    name = hypothesis.name or "Unnamed Strategy"
    pair = varrd_market_to_jesse_pair(market)
    timeframe = varrd_timeframe_to_jesse(market)

    sl_atr = hypothesis.stop_loss_atr
    tp_atr = hypothesis.take_profit_atr
    horizon = hypothesis.selected_horizon

    strategy_class = strategy_name or _sanitize_class_name(name)

    # --- Translate code ---
    indicators_code = ""
    if setup_code:
        indicators_code = varrd_to_jesse_indicators(setup_code)
    if indicators_code:
        lines = indicators_code.split("\n")
        indicators_code = "\n        ".join(lines)
    else:
        indicators_code = "pass  # No setup_code provided"

    entry_expr = varrd_to_jesse_entry(formula)

    # ATR expressions for SL/TP
    sl_expr = atr_to_jesse_sl(sl_atr) if sl_atr is not None else None
    tp_expr = atr_to_jesse_tp(tp_atr) if tp_atr is not None else None

    # --- Clean text fields ---
    explanation = hypothesis.explanation or ""
    if explanation:
        explanation = _comment_wrap(explanation)

    header_name = name.split("\n")[0].strip()
    header_name = header_name.encode("ascii", "replace").decode("ascii")

    # --- Render template ---
    env = Environment(
        loader=FileSystemLoader(str(_TEMPLATE_DIR)),
        keep_trailing_newline=True,
    )
    template = env.get_template("strategy_template.py")

    strategy_content = template.render(
        version="0.1.0",
        hypothesis_name=header_name,
        market=market,
        pair=pair,
        direction=direction,
        timeframe=timeframe,
        has_edge=hypothesis.has_edge,
        win_rate=hypothesis.win_rate,
        sharpe=hypothesis.sharpe,
        ev_per_trade=hypothesis.ev_per_trade,
        profit_factor=hypothesis.profit_factor,
        total_trades=hypothesis.total_trades,
        risk_reward=hypothesis.risk_reward,
        stop_loss_atr=sl_atr,
        take_profit_atr=tp_atr,
        selected_horizon=horizon,
        explanation=explanation,
        strategy_class=strategy_class,
        indicators_code=indicators_code,
        entry_expr=entry_expr,
        sl_expr=sl_expr,
        tp_expr=tp_expr,
        risk_percent=risk_percent,
    )

    # --- Routes file ---
    # Jesse uses routes.py instead of a JSON config
    routes_content = f"""\
# Routes for {header_name}
# Generated by VARRD — https://varrd.com

from jesse.enums import exchanges, timeframes

routes = [
    ('{exchange}', '{pair}', '{timeframe}', '{strategy_class}'),
]

extra_candles = []
"""

    return strategy_content, routes_content
