"""Camacho-Sad index on toy singularities. sympy (exact) + mpmath.iv (interval) + contour quadrature.
Convention (Brunella, Birational geometry of foliations, Ch.3): S={f=0} invariant, foliation form w = g df + f*eta,
CS(F,S,p) = -Res_p( eta/g |_S ).  Sum over sing. pts of compact invariant curve C = C.C."""
import json, itertools
import sympy as sp
from mpmath import iv, mp, quad, exp, pi, mpf, mpc
iv.dps = 40; mp.dps = 30
x,y,u,v,l1,l2,t = sp.symbols('x y u v l1 l2 t')
out = {"convention": "CS = -Res(eta/g|_S), w = g df + f eta (Brunella Ch.3)"}

def form_of(X1,X2):  # w = X2 dx - X1 dy annihilates X1 d/dx + X2 d/dy
    return X2, -X1   # (coeff dx, coeff dy)

def CS_symbolic(A,B,f,var_on_S,xs):
    """w=A dx+B dy ; f in coords xs=(a,b); returns CS along {f=0}, f must be one coordinate."""
    a,b = xs
    assert f==a
    # w = g da + f eta,  g=A (coefficient of da) restricted? need w - g df divisible by f: g = A, eta = B db / a ... only if B divisible by a
    g = sp.simplify(A); rest = sp.simplify(B/a)   # eta = rest db
    ratio = sp.simplify((rest/g).subs(a,0))
    return sp.simplify(-sp.residue(ratio, b, 0))

# (1) linear saddle
A,B = form_of(l1*x, l2*y)           # w = l2 y dx - l1 x dy
cs_y0 = CS_symbolic(B,A,y,x,(y,x)) if False else None
# {y=0}: f=y, coefficient of dy is -l1 x =g, eta = l2 dx  (y*eta = l2 y dx)
cs_y0 = sp.simplify(-sp.residue(sp.simplify((l2/(-l1*x))), x, 0)) # eta/g = l2/(-l1 x) dx
cs_x0 = CS_symbolic(l2*y, -l1*x, x, y, (x,y))
out["1_CS_y0"] = str(cs_y0); out["1_CS_x0"] = str(cs_x0)
assert sp.simplify(cs_y0 - l2/l1)==0 and sp.simplify(cs_x0 - l1/l2)==0

# (2) blow-up, chart1 x=u, y=u v ; chart2 x=u v, y=v
w = (l2*y)*sp.Symbol('dx') - l1*x*sp.Symbol('dy')
def pull(sub, dsub):
    return sp.expand(w.subs({sp.Symbol('dx'):dsub[0], sp.Symbol('dy'):dsub[1]}).subs(sub))
du,dv = sp.symbols('du dv')
w1 = pull({x:u,y:u*v},(du, u*dv+v*du)); w1 = sp.expand(sp.cancel(w1/u))      # chart 1
w2 = pull({x:u*v,y:v},(u*dv+v*du, dv))  # chart2: coordinates (u,v), E={v=0}
w2 = sp.expand(sp.cancel(w2/v))
# chart1: E={u=0}: coefficient of du is g, of dv is u*eta
g1 = w1.coeff(du); eta1 = sp.cancel(w1.coeff(dv)/u)
cs1 = sp.simplify(-sp.residue(sp.simplify((eta1/g1)), v, 0))
g2 = w2.coeff(dv); eta2 = sp.cancel(w2.coeff(du)/v)
cs2 = sp.simplify(-sp.residue(sp.simplify((eta2/g2)), u, 0))
out["2_chart1_form"]=str(w1); out["2_chart2_form"]=str(w2)
out["2_CS_E_at_p1"]=str(cs1); out["2_CS_E_at_p2"]=str(cs2); out["2_sum"]=str(sp.simplify(cs1+cs2))
assert sp.simplify(cs1+cs2+1)==0
# strict transform of {y=0}: v=0 in chart1: f=v, g=coeff dv = -l1 u, eta = coeff du/v = (l2-l1)
cs_tr = sp.simplify(-sp.residue(sp.simplify((l2-l1)/(-l1*u)),u,0))
out["2_CS_strict_y0"]=str(cs_tr)
assert sp.simplify(cs_tr-(l2/l1-1))==0   # CS drops by 1 on each blow-up at a point of S

# interval checks: lambda in boxes, nonresonant (ratio away from 0,1)
def ivcheck(L1,L2):
    c1 = L1/(L2-L1); c2 = L2/(L1-L2); return c1+c2
rows=[]
for a,b in [((1,1),(2,2)),((1,1.0001),(-3,-2.999)),((0.5,0.5001),(0.7,0.7001)),((1,1),(1.5,1.5))]:
    L1=iv.mpf(list(a)); L2=iv.mpf(list(b)); s=ivcheck(L1,L2)
    rows.append({"l1":[str(L1.a),str(L1.b)] if False else list(map(str,a)),"l2":list(map(str,b)),
                 "sum_interval":[iv.nstr(s.a,8) if hasattr(s,'a') else str(s), iv.nstr(s.b,8) if hasattr(s,'b') else ""],
                 "contains_-1": bool(-1 in s)})
out["2_interval_sum_checks"]=rows
# numeric contour check (not certified): CS = -(1/2 pi i) oint eta/g on |.|=r, for lambda complex
def contour(L1,L2):
    r=mpf('0.3'); 
    # chart1 E={u=0}: eta/g = -L1/((L2-L1) v) dv
    f=lambda th: (-L1/((L2-L1)*(r*exp(1j*th))))*(1j*r*exp(1j*th))
    I=quad(f,[0,pi,2*pi]); return -I/(2j*pi)
L1,L2=mpc(1,0.5),mpc(-0.7,2)
out["2_contour_numeric"]={"CS_numeric":str(contour(L1,L2)), "CS_formula":str(L1/(L2-L1))}

# (3) resonant ratio -1/n : l1=n, l2=-1  -> reduced (negative ratio); axes indices -1/n and -n
res3=[]
for n in (1,2,3,4):
    X1 = n*x + 0; X2 = -y
    cs_a = sp.simplify(l2/l1).subs({l1:n,l2:-1}); cs_b = sp.simplify(l1/l2).subs({l1:n,l2:-1})
    # Poincare-Dulac resonant normal form  n x d/dx - y d/dy + x*(x y^n) d/dx? resonant monomials x*(x y^n)^k d/dx, y*(x y^n)^k d/dy
    res3.append({"n":n,"ratio":str(sp.Rational(-1,n)),"CS_y0":str(cs_a),"CS_x0":str(cs_b),
      "reduced":True,"note":"ratio negative => reduced in Seidenberg's sense; resonances exist but no blow-up needed"})
out["3a_negative_ratio"]=res3

# (3b) genuinely non-reduced: ratio n positive integer, X = x dx + n y dy + x^n dy  (Poincare-Dulac, not linearizable)
def blowup_chain(n):
    # iterate chart (x,y)=(u,u v); X=(u, P) -> u'=u, v'=(P(u,uv)-v*u)/u ; track vector field
    X1,X2 = x, n*y + x**n
    steps=[]; k=0
    cx,cy = x,y
    while True:
        lin = sp.Matrix([[sp.diff(X1,x),sp.diff(X1,y)],[sp.diff(X2,x),sp.diff(X2,y)]]).subs({x:0,y:0})
        ev = list(lin.eigenvals().keys())
        steps.append({"k":k,"X":[str(X1),str(X2)],"eigenvalues":[str(e) for e in ev]})
        if X1.subs({x:0,y:0})!=0 or X2.subs({x:0,y:0})!=0 or all(e==0 for e in ev) is False and False: pass
        if lin==sp.zeros(2) or (X1.subs({x:0,y:0})==0 and X2.subs({x:0,y:0})==0)==False: break
        # chart 1 blow-up: new coordinates (u,v)
        N1 = sp.expand(X1.subs({x:u,y:u*v}))
        N2 = sp.expand(sp.cancel((X2.subs({x:u,y:u*v}) - v*N1)/u))
        X1,X2 = N1.subs(u,x), N2.subs({u:x,v:y}); k+=1
        if k>n+2: break
    return steps
out["3b_nonreduced_chain"]={n:blowup_chain(n) for n in (1,2,3,4)}
# CS of invariant {x=0} for X = x d/dx + n y d/dy + x^n d/dy:  w=(n y+x^n)dx - x dy ; f=x,g=n y+x^n, eta=-dy
cs3b = sp.simplify(-sp.residue(sp.simplify(-1/(n_:=sp.Symbol('n')*y)), y, 0))
out["3b_CS_x0"]=str(cs3b)+"  (=1/n, same as linear part; resonant term invisible to CS)"
json.dump(out,open('compute/camacho-sad-results.json','w'),indent=1,default=str)
print(json.dumps(out,indent=1,default=str)[:6000])
