"""PC estable para gaussianas y NOTEARS lineal con datos estandarizados."""
from itertools import combinations
import numpy as np
import networkx as nx
from scipy.linalg import expm
from scipy.optimize import minimize
from scipy.stats import norm

def partial_pvalue(data,i,j,cond):
    n=len(data);cols=[i,j,*cond]
    if n-len(cond)-3<=0:return 1.
    cov=np.corrcoef(data[:,cols],rowvar=False)
    precision=np.linalg.pinv(cov);r=-precision[0,1]/np.sqrt(precision[0,0]*precision[1,1])
    r=np.clip(r,-1+1e-12,1-1e-12)
    stat=np.sqrt(n-len(cond)-3)*abs(np.arctanh(r))
    return float(2*norm.sf(stat))

def pc_skeleton(data,alpha=.05,max_cond=None,trace=None):
    X=np.asarray(data,float)
    if X.ndim!=2 or not np.isfinite(X).all() or not 0<alpha<1:raise ValueError('Datos o alpha inválidos')
    d=X.shape[1];adj=np.ones((d,d),dtype=bool);np.fill_diagonal(adj,False);seps={};depth=0
    if trace is not None:trace.append({'depth':-1,'adj':adj.astype(int).tolist(),'removed':[]})
    limit=d-2 if max_cond is None else max_cond
    while depth<=limit:
        frozen=adj.copy();removals=[];found_candidate=False
        for i in range(d):
            for j in range(i+1,d):
                if not frozen[i,j]:continue
                for source,target in ((i,j),(j,i)):
                    neighbors=[v for v in range(d) if frozen[source,v] and v!=target]
                    if len(neighbors)<depth:continue
                    found_candidate=True
                    for cond in combinations(neighbors,depth):
                        if partial_pvalue(X,i,j,cond)>alpha:
                            removals.append((i,j,tuple(cond)));break
                    if removals and removals[-1][:2]==(i,j):break
        for i,j,cond in removals:adj[i,j]=adj[j,i]=False;seps[(i,j)]=seps[(j,i)]=cond
        if trace is not None:trace.append({'depth':depth,'adj':adj.astype(int).tolist(),
                                           'removed':[[i,j,list(cond)] for i,j,cond in removals]})
        if not found_candidate:break
        depth+=1
    return adj,seps

def pc_orient(adj,seps):
    """V-estructuras y reglas de Meek R1-R3; devuelve matriz de arcos."""
    A=adj.astype(int).copy();d=len(A)
    def edge(a,b):return bool(A[a,b] or A[b,a])
    def undirected(a,b):return A[a,b]==1 and A[b,a]==1
    def arrow(a,b):return A[a,b]==1 and A[b,a]==0
    def orient(a,b):
        if undirected(a,b):A[b,a]=0;return True
        return False
    for j in range(d):
        for i,k in combinations([x for x in range(d) if adj[j,x]],2):
            if not adj[i,k] and j not in seps.get((i,k),()):orient(i,j);orient(k,j)
    changed=True
    while changed:
        changed=False
        for a in range(d):
            for b in range(d):
                if not undirected(a,b):continue
                r1=any(arrow(c,a) and not edge(c,b) for c in range(d) if c not in (a,b))
                r2=any(arrow(a,c) and arrow(c,b) for c in range(d) if c not in (a,b))
                candidates=[c for c in range(d) if c not in (a,b) and undirected(a,c) and arrow(c,b)]
                r3=any(not edge(c,e) for c,e in combinations(candidates,2))
                if r1 or r2 or r3:changed=orient(a,b) or changed
    return A

def pc(data,alpha=.05,max_cond=None,trace=None):
    adj,seps=pc_skeleton(data,alpha,max_cond,trace)
    return pc_orient(adj,seps),adj,seps

def simulate(seed,d,n,noise):
    rng=np.random.default_rng(seed);W=np.zeros((d,d))
    for i in range(d):
        for j in range(i+1,d):
            if rng.random()<2/(d-1):W[i,j]=rng.choice([-1,1])*rng.uniform(.5,1.2)
    X=np.zeros((n,d))
    for j in range(d):
        scale=1. if j==0 else noise
        X[:,j]=X@W[:,j]+rng.normal(0,scale,n)
    X=(X-X.mean(axis=0))/X.std(axis=0,ddof=0)
    return X,W

def notears(X,l1=.05,threshold=.3,max_outer=30,h_tol=1e-8):
    X=np.asarray(X,float);n,d=X.shape
    if not np.isfinite(X).all():raise ValueError('Datos no finitos')
    def unpack(z):return z[:d*d].reshape(d,d)-z[d*d:].reshape(d,d)
    bounds=[(0,0) if i==j else (0,None) for i in range(d) for j in range(d)]*2
    z=np.zeros(2*d*d);rho=1.;alpha=0.;old_h=np.inf
    for _ in range(max_outer):
        while rho<1e16:
            def objective(z):
                W=unpack(z);R=X-X@W;E=expm(W*W);h=np.trace(E)-d
                loss=.5*np.sum(R*R)/n+l1*np.sum(z)+alpha*h+.5*rho*h*h
                grad=X.T@(-R)/n+(alpha+rho*h)*(E.T*(2*W))
                return loss,np.r_[(grad+l1).ravel(),(-grad+l1).ravel()]
            result=minimize(objective,z,method='L-BFGS-B',jac=True,bounds=bounds)
            W=unpack(result.x);h=float(np.trace(expm(W*W))-d)
            if h>old_h*.25:rho*=10
            else:break
        z=result.x;old_h=h;alpha+=rho*h
        if h<=h_tol or rho>=1e16:break
    W=unpack(z);W[np.abs(W)<threshold]=0
    graph=nx.from_numpy_array(W,create_using=nx.DiGraph);removed=0
    while not nx.is_directed_acyclic_graph(graph):
        cycle=nx.find_cycle(graph);edge=min(cycle,key=lambda e:abs(W[e[0],e[1]]));W[edge[0],edge[1]]=0
        graph.remove_edge(*edge);removed+=1
    return W,{'h_before_threshold':h,'removed_cycle_edges':removed,'optimizer_success':bool(result.success)}

def shd_mixed(estimate,truth):
    """Una discrepancia por par: ausente, no orientado o cada orientación."""
    a=np.asarray(estimate);b=np.asarray(truth);d=len(a)
    return int(sum((int(a[i,j]),int(a[j,i]))!=(int(b[i,j]),int(b[j,i]))
                   for i in range(d) for j in range(i+1,d)))
