"""Pro-rated Profit Target calculation."""
from __future__ import annotations
from app.engine.base import BaseAlgorithm
from app.engine.context import AlgorithmContext


class ProratedProfitAlgorithm(BaseAlgorithm):
    algorithm_id = 'quantitative.prorated_profit'
    version = '1.0.0'
    category = 'quantitative'
    display_name = 'Pro-rated Profit Target'
    dependencies = ['technical.atr']

    def __init__(self, targets_pct=None):
        self.targets_pct = targets_pct or [1.0, 2.0, 3.0, 5.0, 10.0]

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

        buy_fee = ctx.buy_fee_pct / 100
        sell_fee = ctx.sell_fee_pct / 100
        total_fee_pct = ctx.buy_fee_pct + ctx.sell_fee_pct

        capital = ctx.capital_idr * (ctx.active_pct / 100)
        buy_cost = capital * (1 + buy_fee)
        units = capital / price

        targets = []
        for pct in self.targets_pct:
            sell_price = price * (1 + pct / 100)
            gross_revenue = units * sell_price
            sell_fee_amount = gross_revenue * sell_fee
            net_revenue = gross_revenue - sell_fee_amount
            buy_fee_amount = capital * buy_fee

            gross_profit = net_revenue - buy_cost
            net_profit = gross_profit
            net_profit_pct = net_profit / capital * 100

            # Breakeven: price where net_profit = 0
            # net_revenue = buy_cost → units * sell_price * (1-sell_fee) = capital * (1+buy_fee)
            breakeven_price = capital * (1 + buy_fee) / (units * (1 - sell_fee))

            targets.append({
                'target_pct': pct,
                'sell_price': float(sell_price),
                'gross_profit_idr': float(gross_revenue - capital),
                'net_profit_idr': float(net_profit),
                'net_profit_pct': float(net_profit_pct),
                'fee_total_idr': float(buy_fee_amount + sell_fee_amount),
            })

        breakeven = float(capital * (1 + buy_fee) / (units * (1 - sell_fee)))
        breakeven_pct = (breakeven / price - 1) * 100

        ctx.quantitative['prorated_profit'] = {
            'entry_price': float(price),
            'capital_idr': float(capital),
            'units': float(units),
            'total_fee_roundtrip_pct': float(total_fee_pct),
            'breakeven_price': breakeven,
            'breakeven_pct': float(breakeven_pct),
            'targets': targets,
        }
        return ctx
