"""Capital Allocator - per-asset capital allocation from database.

Loads and calculates per-asset capital allocation, supporting
custom allocations and fallback to default.
"""
from __future__ import annotations
from app.engine.base import BaseAlgorithm
from app.engine.context import AlgorithmContext


class CapitalAllocatorAlgorithm(BaseAlgorithm):
    algorithm_id = 'money_mgmt.capital_allocator'
    version = '1.0.0'
    category = 'money_management'
    display_name = 'Capital Allocator'
    dependencies = ['money_mgmt.fixed_fractional']

    def compute(self, ctx: AlgorithmContext) -> AlgorithmContext:
        # Try to load per-asset allocation from database
        coin_allocation = self._load_allocation(ctx.asset_id)

        if coin_allocation:
            allocated = coin_allocation['allocated_capital_idr']
            active_pct = coin_allocation['active_capital_pct']
            reserve_pct = coin_allocation['reserve_capital_pct']
        else:
            # Fallback to global settings
            allocated = ctx.capital_idr
            active_pct = ctx.active_pct
            reserve_pct = ctx.reserve_pct

        active_amount = allocated * (active_pct / 100)
        reserve_amount = allocated * (reserve_pct / 100)

        # Position limits for this asset
        max_per_trade = active_amount * 0.25  # 25% of active per trade
        daily_limit = active_amount * 0.50    # 50% max exposure per day

        ctx.money_mgmt['capital_allocator'] = {
            'asset_id': ctx.asset_id,
            'allocated_capital': round(allocated, 0),
            'active_capital': round(active_amount, 0),
            'reserve_capital': round(reserve_amount, 0),
            'active_pct': active_pct,
            'reserve_pct': reserve_pct,
            'max_per_trade': round(max_per_trade, 0),
            'daily_limit': round(daily_limit, 0),
            'is_custom': coin_allocation is not None,
        }
        return ctx

    def _load_allocation(self, asset_id):
        """Load per-asset allocation from database."""
        try:
            from app.models.settings import CapitalAllocation
            alloc = CapitalAllocation.query.filter_by(asset_id=asset_id).first()
            if alloc:
                return {
                    'allocated_capital_idr': float(alloc.allocated_capital_idr),
                    'active_capital_pct': float(alloc.active_capital_pct),
                    'reserve_capital_pct': float(alloc.reserve_capital_pct),
                }
        except Exception:
            pass
        return None
