"""TWAP — Time-Weighted Average Price execution algorithm.

Splits a parent order into equal slices submitted at regular intervals
over a specified duration.
"""

from __future__ import annotations

import math
import time
from typing import Any, Dict, List

from ..models import OrderSubmitRequest
from .base import AlgoSlice, ExecAlgorithm


class TWAPAlgorithm(ExecAlgorithm):
    """Time-Weighted Average Price.

    Params:
        duration_minutes (float): Total execution window (default 30).
        num_slices (int): Number of child orders (default 10).
    """

    name = "twap"

    def generate_slices(
        self, req: OrderSubmitRequest, params: Dict[str, Any]
    ) -> List[AlgoSlice]:
        duration_min = float(params.get("duration_minutes", 30))
        num_slices = int(params.get("num_slices", 10))

        total_qty = req.qty or 0
        if total_qty <= 0:
            raise ValueError("TWAP requires qty > 0")

        if num_slices < 1:
            num_slices = 1

        base_qty = math.floor(total_qty / num_slices)
        remainder = total_qty - base_qty * num_slices
        interval_sec = (duration_min * 60) / num_slices
        now = time.time()

        slices: List[AlgoSlice] = []
        for i in range(num_slices):
            qty = base_qty + (1 if i < remainder else 0)
            if qty <= 0:
                continue
            slices.append(
                AlgoSlice(
                    seq=i,
                    symbol=req.symbol,
                    side=req.side.value,
                    qty=qty,
                    order_type="market",
                    scheduled_time=now + i * interval_sec,
                )
            )
        return slices
