import numpy as np
import pandas as pd
import pytest
from p01data import total_return, asof_versions, fetch, sha256, compare_universes, Order, Fill

def test_total_return_split_dividendo():
    got=total_return([100,51,52],[0,.5,0],[1,2,1])
    assert np.isnan(got[0])
    assert np.allclose(got[1:],[.03,52/51-1])

def test_evento_invalido():
    with pytest.raises(ValueError): total_return([100,50],[0,0],[1,0])

def test_revision_disponible():
    x=pd.DataFrame({"activo":["A","A"],"fecha":["2020-01-01"]*2,
                    "disponible":["2020-01-02T00:00:00Z","2020-02-01T00:00:00Z"],"valor":[1.,2.]})
    assert asof_versions(x,"2020-01-15T00:00:00Z").iloc[0].valor==1
    assert asof_versions(x,"2020-03-01T00:00:00Z").iloc[0].valor==2
    assert len(asof_versions(x,"2020-01-01T00:00:00Z"))==0

def test_hash_cache(tmp_path):
    path=tmp_path/"data"; path.write_bytes(b"version")
    assert fetch("https://example.invalid/",path,sha256(b"version"))==b"version"
    with pytest.raises(ValueError): fetch("https://example.invalid/",path,"0"*64)

def test_universo_historico(tmp_path):
    dates=pd.date_range("2020-01-01",periods=3)
    p=pd.DataFrame([(d,t,v,"demo") for t,vals in {"A":[100,100,100],"B":[100,50,25],"C":[100,150,225]}.items() for d,v in zip(dates,vals)],
                   columns=["date","ticker","adj_close","source"])
    m=pd.DataFrame({"ticker":["A","B","C"],"start":pd.to_datetime(["2020-01-01","2020-01-01","2020-01-03"]),
                    "end":pd.to_datetime([None,"2020-01-03",None])})
    p.to_parquet(tmp_path/"p.parquet",index=False);m.to_parquet(tmp_path/"m.parquet",index=False)
    comparison,info=compare_universes(tmp_path/"p.parquet",tmp_path/"m.parquet","2020-01-02","2020-01-03")
    assert np.isclose(comparison.loc["2020-01-03","historico"],-.25)
    assert np.isclose(comparison.loc["2020-01-03","corte"],.25)
    assert info["miembros_corte"]==2

def test_flujo_de_contratos():
    class Data:
        def history(self,symbol,asof): return pd.DataFrame({"close":[100.]},index=[asof])
    class Signal:
        def decide(self,history): return float(history.close.iloc[-1]>90)
    class Portfolio:
        def target(self,signals): return signals
    class Execution:
        def fill(self,order,market): return Fill(order.symbol,order.quantity,float(market.close.iloc[-1]),1.,order.created_at)
    class Ledger:
        def __init__(self): self.cash=1000.;self.q=0.
        def apply(self,fill): self.cash-=fill.quantity*fill.price+fill.cost;self.q+=fill.quantity
        def equity(self,marks): return self.cash+self.q*marks["A"]
    class Analysis:
        def report(self,equity): return {"final":float(equity.iloc[-1])}
    time=pd.Timestamp("2020-01-02",tz="UTC"); bars=Data().history("A",time)
    target=Portfolio().target({"A":Signal().decide(bars)})
    fill=Execution().fill(Order("A",target["A"],time),bars); ledger=Ledger();ledger.apply(fill)
    assert ledger.q==1 and ledger.cash==899.
    assert Analysis().report(pd.Series([ledger.equity({"A":100.})]))["final"]==999.
