"""Ghost Mode - Order Splitting for stealth execution.

Splits large orders into smaller tranches to minimize market impact.
Adapted from behavioral finance best practices.
"""
from __future__ import annotations
import math
from app.engine.base import BaseAlgorithm
from app.engine.context import AlgorithmContext


class OrderSplittingAlgorithm(BaseAlgorithm):
    algorithm_id = 'behavioral.order_splitting'
    version = '1.0.0'
    category = 'behavioral'
    display_name = 'Ghost Mode (Order Splitting)'
    dependencies = ['technical.atr']

    def __init__(self, max_tranches: int = 5, volume_pct_limit: float = 2.0):
        """
        Args:
            max_tranches: Maximum number of order splits
            volume_pct_limit: Max % of avg volume per tranche (stealth limit)
        """
        self.max_tranches = max_tranches
        self.volume_pct_limit = volume_pct_limit

    def compute(self, ctx: AlgorithmContext) -> AlgorithmContext:
        price = ctx.current_price
        if not price:
            return ctx

        active_capital = ctx.capital_idr * (ctx.active_pct / 100)
        total_order_value = active_capital * 0.25  # 25% per trade

        # Calculate average volume in IDR
        df = ctx.ohlcv
        if df is not None and len(df) >= 5:
            avg_vol = df['volume'].tail(20).mean()
            avg_vol_idr = avg_vol * price
        else:
            avg_vol_idr = total_order_value * 100  # assume liquid

        # Volume limit per tranche
        max_per_tranche = avg_vol_idr * (self.volume_pct_limit / 100)

        # How many tranches needed to stay under volume limit
        if max_per_tranche > 0:
            min_tranches = math.ceil(total_order_value / max_per_tranche)
        else:
            min_tranches = 1

        num_tranches = max(min_tranches, 2)  # at least 2 splits
        num_tranches = min(num_tranches, self.max_tranches)

        tranche_value = total_order_value / num_tranches
        tranche_qty = tranche_value / price if price > 0 else 0

        # Stealth score: how visible is this order?
        # Lower = more stealthy
        visibility = (tranche_value / avg_vol_idr * 100) if avg_vol_idr > 0 else 100
        stealth_score = max(0, min(100, 100 - visibility * 10))

        # Recommended interval between tranches (minutes)
        atr = ctx.indicators.get('atr_latest', 0)
        atr_pct = (atr / price * 100) if price > 0 else 1
        if atr_pct > 3:
            interval_mins = 5   # volatile: execute fast
        elif atr_pct > 1:
            interval_mins = 15  # moderate: spread out
        else:
            interval_mins = 30  # calm: can wait

        tranches = []
        for i in range(num_tranches):
            tranches.append({
                'tranche': i + 1,
                'value_idr': round(tranche_value, 0),
                'quantity': float(tranche_qty),
                'delay_minutes': interval_mins * i,
            })

        ctx.quantitative['order_splitting'] = {
            'total_order_value': round(total_order_value, 0),
            'num_tranches': num_tranches,
            'tranche_value_idr': round(tranche_value, 0),
            'tranche_quantity': float(tranche_qty),
            'interval_minutes': interval_mins,
            'stealth_score': round(stealth_score, 1),
            'volume_impact_pct': round(visibility, 2),
            'tranches': tranches,
        }
        return ctx
