"""Funções financeiras puras — espelha src/features/analise/finance.ts.

Implementações:
- VPL: somatório direto (igual ao JS).
- TIR: bisseção (mesmo algoritmo do JS, garante paridade numérica).
- Payback simples e descontado.
"""
import math
from dataclasses import dataclass
from typing import List


def vpl(taxa: float, fluxos: List[float]) -> float:
    return sum(cf / ((1 + taxa) ** i) for i, cf in enumerate(fluxos))


def tir(fluxos: List[float], tol: float = 1e-7, max_iter: int = 1000) -> float:
    if not (any(v > 0 for v in fluxos) and any(v < 0 for v in fluxos)):
        return math.nan
    a, b = -0.999, 10.0
    fa, fb = vpl(a, fluxos), vpl(b, fluxos)
    if fa * fb > 0:
        return math.nan
    for _ in range(max_iter):
        c = (a + b) / 2
        fc = vpl(c, fluxos)
        if abs(fc) < tol or (b - a) / 2 < tol:
            return c
        if fa * fc < 0:
            b, fb = c, fc
        else:
            a, fa = c, fc
    return (a + b) / 2


@dataclass
class PaybackResult:
    periodo_simples: float
    periodo_descontado: float


def payback(fluxos: List[float], tma: float) -> PaybackResult:
    acum_s = 0.0
    acum_d = 0.0
    p_s = math.nan
    p_d = math.nan
    for i, cf in enumerate(fluxos):
        acum_s += cf
        acum_d += cf / ((1 + tma) ** i)
        if math.isnan(p_s) and acum_s >= 0:
            p_s = i
        if math.isnan(p_d) and acum_d >= 0:
            p_d = i
    return PaybackResult(p_s, p_d)
