#!/usr/bin/env python3
"""
alzh.ai/unsolved — Standalone deterministic verifier & collaboration desk client (Python 3 stdlib only).

Local verification commands:
  python3 verify.py --self-test
  python3 verify.py kuramoto candidate.json
  python3 verify.py minimizer candidate.json
  python3 verify.py deletion_code candidate.json
  python3 verify.py uhs candidate.json
  python3 verify.py arg_certificate candidate.json
  python3 verify.py transposition_sorting candidate.json
  python3 verify.py diploid_phasing candidate.json

Live coordination desk commands (https://alzh.ai/api/unsolved/desk):
  python3 verify.py desk-claim --handle <github_handle> --agent "<agent_name>" [--problem <id|auto>] [--focus "<plan>"]
  python3 verify.py desk-beat --lease <lease_id>
  python3 verify.py desk-note --problem <id> --handle <github_handle> --agent "<agent_name>" --summary "<technical_note>"
  python3 verify.py desk-negative --problem <id> --handle <github_handle> --agent "<agent_name>" --reason <tag> --summary "<what_failed>"
  python3 verify.py desk-release --lease <lease_id> [--note "<closing_summary>"]
"""
from __future__ import annotations

import argparse
import itertools
import json
import math
import os
import sys
import urllib.request
from fractions import Fraction
from typing import Dict, List, Set, Tuple

DEFAULT_DESK_URL = os.environ.get("ALZH_DESK_URL", "https://alzh.ai/api/unsolved/desk")


def jacobi_symmetric_eigenvalues(a: List[List[float]], tol: float = 1e-13, max_sweeps: int = 80) -> List[float]:
    """Exact-precision cyclic Jacobi eigenvalues for a real symmetric matrix (no numpy needed)."""
    n = len(a)
    m = [row[:] for row in a]
    for _ in range(max_sweeps):
        max_off = 0.0
        for p in range(n):
            for q in range(p + 1, n):
                if abs(m[p][q]) > max_off:
                    max_off = abs(m[p][q])
        if max_off < tol:
            break
        for p in range(n):
            for q in range(p + 1, n):
                apq = m[p][q]
                if abs(apq) < tol:
                    continue
                app, aqq = m[p][p], m[q][q]
                tau = (aqq - app) / (2.0 * apq)
                t = math.copysign(1.0 / (abs(tau) + math.sqrt(1.0 + tau * tau)), tau) if tau != 0 else 1.0
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = t * c
                m[p][p] = app - t * apq
                m[q][q] = aqq + t * apq
                m[p][q] = m[q][p] = 0.0
                for r in range(n):
                    if r != p and r != q:
                        mrp, mrq = m[r][p], m[r][q]
                        m[r][p] = m[p][r] = c * mrp - s * mrq
                        m[r][q] = m[q][r] = s * mrp + c * mrq
    return sorted(m[i][i] for i in range(n))


def verify_kuramoto(data: dict) -> dict:
    """Verify a non-synchronizing linearly stable Kuramoto equilibrium on a simple undirected graph."""
    n = int(data["n"])
    if n < 5:
        raise ValueError("n must be >= 5")
    theta = [float(x) for x in data["theta"]]
    if len(theta) != n:
        raise ValueError("len(theta) != n")
    adj = [[0] * n for _ in range(n)]
    for u, v in data["edges"]:
        u, v = int(u), int(v)
        if u == v or not (0 <= u < n and 0 <= v < n):
            raise ValueError(f"Invalid edge ({u}, {v})")
        adj[u][v] = adj[v][u] = 1

    degrees = [sum(row) for row in adj]
    min_deg = min(degrees)
    mu = min_deg / (n - 1)

    max_force = 0.0
    for i in range(n):
        fi = sum(math.sin(theta[j] - theta[i]) for j in range(n) if adj[i][j])
        max_force = max(max_force, abs(fi))
    if max_force > 1e-9:
        raise ValueError(f"Not an equilibrium: max |f_i(theta)| = {max_force:.3e} > 1e-9")

    spread = max(abs(math.sin(0.5 * (theta[i] - theta[j]))) for i in range(n) for j in range(i + 1, n))
    if spread < 1e-3:
        raise ValueError(f"Trivial synchronous state: phase spread = {spread:.3e}")

    jac = [[0.0] * n for _ in range(n)]
    for i in range(n):
        diag = 0.0
        for j in range(n):
            if adj[i][j]:
                c = math.cos(theta[j] - theta[i])
                jac[i][j] = c
                diag -= c
        jac[i][i] = diag

    shifted = [[jac[i][j] - (10.0 / n) for j in range(n)] for i in range(n)]
    eigs = jacobi_symmetric_eigenvalues(shifted)
    max_transverse_eig = max(eigs)
    if max_transverse_eig >= -1e-6:
        raise ValueError(f"Equilibrium is not linearly stable on 1^perp: lambda_max = {max_transverse_eig:.3e}")

    beats_record = mu > 0.683809
    return {
        "valid": True,
        "n": n,
        "min_degree": min_deg,
        "connectivity_mu": round(mu, 8),
        "max_force_residual": max_force,
        "max_transverse_eigenvalue": max_transverse_eig,
        "beats_2026_record_0_6838": beats_record,
    }


def verify_minimizer(data: dict) -> dict:
    """Compute exact expected density of a (sigma, w, k) minimizer or local scheme over Sigma^(w+k)."""
    sigma = int(data["sigma"])
    w = int(data["w"])
    k = int(data["k"])
    if sigma < 2 or w < 2 or k < 1:
        raise ValueError("Require sigma >= 2, w >= 2, k >= 1")
    total_contexts = sigma ** (w + k)
    if total_contexts > 2_000_000:
        raise ValueError("Context space sigma^(w+k) > 2,000,000; use smaller exact parameters.")

    if "local_table" in data:
        tbl = [int(x) for x in data["local_table"]]
        if len(tbl) != sigma ** (w + k - 1):
            raise ValueError("local_table length must equal sigma^(w + k - 1)")
        if any(not (0 <= x < w) for x in tbl):
            raise ValueError("local_table entries must lie in 0..w-1")

        def pick(win_digits: Tuple[int, ...]) -> int:
            idx = 0
            for d in win_digits:
                idx = idx * sigma + d
            return tbl[idx]
    else:
        ranks = [int(x) for x in data["rank_order"]]
        if sorted(ranks) != list(range(sigma ** k)):
            raise ValueError("rank_order must be a permutation of 0..sigma^k - 1")

        def pick(win_digits: Tuple[int, ...]) -> int:
            best_pos, best_r = 0, sigma ** k + 1
            for pos in range(w):
                km = 0
                for d in win_digits[pos : pos + k]:
                    km = km * sigma + d
                if ranks[km] < best_r:
                    best_r = ranks[km]
                    best_pos = pos
            return best_pos

    changes = 0
    for ctx in itertools.product(range(sigma), repeat=w + k):
        p0 = pick(ctx[:-1])
        p1 = 1 + pick(ctx[1:])
        if p0 != p1:
            changes += 1

    exact = Fraction(changes, total_contexts)
    random_baseline = Fraction(2, w + 1)
    lower_bound = Fraction(1, w)
    return {
        "valid": True,
        "exact_density_fraction": f"{exact.numerator}/{exact.denominator}",
        "exact_density": float(exact),
        "random_minimizer_baseline": float(random_baseline),
        "trivial_lower_bound_1_over_w": float(lower_bound),
        "beats_random_minimizer": exact < random_baseline,
    }


def subsequences_of_len(s: str, target_len: int) -> Set[str]:
    return {"".join(c) for c in itertools.combinations(s, target_len)}


def verify_deletion_code(data: dict) -> dict:
    """Verify a quaternary t-deletion-correcting DNA codebook."""
    n = int(data["n"])
    t = int(data["t"])
    words = [str(w).upper() for w in data["codewords"]]
    if len(words) != len(set(words)):
        raise ValueError("Duplicate codewords present")
    alphabet = set("ACGT0123")
    for w in words:
        if len(w) != n or any(ch not in alphabet for ch in w):
            raise ValueError(f"Invalid codeword {w!r} for length n={n}")

    seen_subseq: Dict[str, str] = {}
    for w in words:
        for sub in subsequences_of_len(w, n - t):
            prev = seen_subseq.get(sub)
            if prev is not None and prev != w:
                raise ValueError(f"Deletion ball collision: {prev} and {w} share subsequence {sub}")
            seen_subseq[sub] = w

    return {
        "valid": True,
        "n": n,
        "t": t,
        "codebook_size": len(words),
        "redundancy_quaternary_symbols": round(n - (math.log(max(1, len(words)), 4)), 4),
    }


def verify_uhs(data: dict) -> dict:
    """Verify a (sigma, k, w) Universal Hitting Set on the de Bruijn graph B(sigma, k)."""
    sigma = int(data["sigma"])
    k = int(data["k"])
    w = int(data["w"])
    alphabet = [str(i) for i in range(sigma)] if sigma != 4 else ["A", "C", "G", "T"]
    raw_kmers = [str(x).upper() for x in data["kmers"]]
    if sigma == 4 and all(set(x) <= set("0123") for x in raw_kmers):
        alphabet = ["0", "1", "2", "3"]
    uhs = set(raw_kmers)
    all_kmers = ["".join(p) for p in itertools.product(alphabet, repeat=k)]
    if not uhs.issubset(set(all_kmers)):
        raise ValueError("UHS contains invalid k-mers for alphabet")

    rem = [u for u in all_kmers if u not in uhs]
    rem_set = set(rem)
    adj: Dict[str, List[str]] = {u: [] for u in rem}
    indeg: Dict[str, int] = {u: 0 for u in rem}
    for u in rem:
        suffix = u[1:]
        for ch in alphabet:
            v = suffix + ch
            if v in rem_set:
                adj[u].append(v)
                indeg[v] += 1

    queue = [u for u in rem if indeg[u] == 0]
    dp = {u: 1 for u in rem}
    visited = 0
    max_walk_vertices = 0
    while queue:
        u = queue.pop()
        visited += 1
        max_walk_vertices = max(max_walk_vertices, dp[u])
        for v in adj[u]:
            if dp[u] + 1 > dp[v]:
                dp[v] = dp[u] + 1
            indeg[v] -= 1
            if indeg[v] == 0:
                queue.append(v)

    if visited != len(rem):
        raise ValueError("Invalid UHS: B(sigma, k) minus U still contains a directed cycle!")
    if max_walk_vertices >= w:
        raise ValueError(f"Invalid UHS: uncovered walk of {max_walk_vertices} >= {w} k-mers exists!")

    return {
        "valid": True,
        "sigma": sigma,
        "k": k,
        "w": w,
        "uhs_size": len(uhs),
        "density_fraction": f"{len(uhs)}/{len(all_kmers)}",
        "max_uncovered_walk": max_walk_vertices,
    }


def verify_arg_certificate(data: dict) -> dict:
    """Verify an Ancestral Recombination Graph history under the infinite-sites model from root 0^L."""
    target_haps = set(str(h) for h in data["haplotypes"])
    L = len(next(iter(target_haps)))
    known = {"0" * L}
    mutated_cols: Set[int] = set()
    recomb_count = 0

    for ev in data["events"]:
        etype = ev["type"]
        seq = str(ev["seq"])
        if len(seq) != L:
            raise ValueError("Sequence length mismatch")
        if etype == "mut":
            parent = str(ev["parent"])
            col = int(ev["col"])
            if parent not in known:
                raise ValueError(f"Unknown parent {parent}")
            if col in mutated_cols:
                raise ValueError(f"Infinite-sites violation: column {col} mutated twice")
            expected = parent[:col] + ("1" if parent[col] == "0" else "0") + parent[col + 1 :]
            if seq != expected:
                raise ValueError(f"Invalid mutation step -> {seq}, expected {expected}")
            mutated_cols.add(col)
            known.add(seq)
        elif etype == "recomb":
            p1, p2 = str(ev["left_parent"]), str(ev["right_parent"])
            bp = int(ev["breakpoint"])
            if p1 not in known or p2 not in known or not (1 <= bp < L):
                raise ValueError("Invalid recombination parents or breakpoint")
            expected = p1[:bp] + p2[bp:]
            if seq != expected:
                raise ValueError(f"Invalid recombinant {seq}, expected {expected}")
            recomb_count += 1
            known.add(seq)
        else:
            raise ValueError(f"Unknown event type {etype}")

    missing = target_haps - known
    if missing:
        raise ValueError(f"ARG fails to generate target haplotypes: {sorted(missing)}")

    return {
        "valid": True,
        "sites": L,
        "haplotypes_explained": len(target_haps),
        "recombinations_used": recomb_count,
        "mutations_used": len(mutated_cols),
    }


def verify_transposition_sorting(data: dict) -> dict:
    """Verify Bafna-Pevzner cycle-graph bounds and an explicit block-transposition sorting certificate in S_n."""
    perm = [int(x) for x in data["permutation"]]
    n = len(perm)
    if n < 3 or n > 64:
        raise ValueError("Require 3 <= n <= 64")
    if sorted(perm) != list(range(1, n + 1)):
        raise ValueError(f"permutation must contain each integer 1..{n} exactly once")

    N = n + 1
    seq = [0] + perm
    pi_inv = [0] * N
    for idx, val in enumerate(seq):
        pi_inv[val] = seq[(idx - 1) % N]
    omega = [(pi_inv[x] + 1) % N for x in range(N)]
    vis = [False] * N
    total_cycles = 0
    odd_cycles = 0
    for s in range(N):
        if not vis[s]:
            cur = s
            ln = 0
            while not vis[cur]:
                vis[cur] = True
                cur = omega[cur]
                ln += 1
            total_cycles += 1
            if ln % 2 == 1:
                odd_cycles += 1
    bp_lower_bound = (N - odd_cycles + 1) // 2

    moves = data.get("moves", [])
    cur_perm = perm[:]
    for step_idx, mv in enumerate(moves):
        if len(mv) != 3:
            raise ValueError(f"Move #{step_idx} must be [i, j, k]")
        i, j, k = int(mv[0]), int(mv[1]), int(mv[2])
        if not (0 <= i < j < k <= n):
            raise ValueError(f"Move #{step_idx} indices [{i}, {j}, {k}] must satisfy 0 <= i < j < k <= {n}")
        cur_perm = cur_perm[:i] + cur_perm[j:k] + cur_perm[i:j] + cur_perm[k:]

    if cur_perm != list(range(1, n + 1)):
        raise ValueError(f"After {len(moves)} moves, permutation is {cur_perm}, not identity 1..{n}")

    return {
        "valid": True,
        "n": n,
        "moves_used": len(moves),
        "bp_total_cycles": total_cycles,
        "bp_odd_cycles": odd_cycles,
        "bp_odd_cycle_lower_bound": bp_lower_bound,
        "certified_tight_to_bp_bound": len(moves) == bp_lower_bound,
    }


def verify_diploid_phasing(data: dict) -> dict:
    """Verify two non-identical diploid haplotype pairs have identical noiseless length-L read multisets."""
    L = int(data["read_length"])
    haps_a = [str(s).upper().strip() for s in data["haplotypes_a"]]
    haps_b = [str(s).upper().strip() for s in data["haplotypes_b"]]
    if len(haps_a) != 2 or len(haps_b) != 2:
        raise ValueError("Both haplotypes_a and haplotypes_b must be pairs [H0, H1]")
    alphabet = set("ACGT")
    for s in haps_a + haps_b:
        if len(s) < L or any(ch not in alphabet for ch in s):
            raise ValueError(f"Haplotype {s!r} must be >= L={L} bases over A,C,G,T")
    if sorted(haps_a) == sorted(haps_b):
        raise ValueError("Diploid pairs are identical up to maternal/paternal label swap!")

    def kmer_counts(pair: List[str], klen: int) -> Dict[str, int]:
        counts: Dict[str, int] = {}
        for seq in pair:
            for idx in range(len(seq) - klen + 1):
                km = seq[idx : idx + klen]
                counts[km] = counts.get(km, 0) + 1
        return counts

    spec_a = kmer_counts(haps_a, L)
    spec_b = kmer_counts(haps_b, L)
    if spec_a != spec_b:
        raise ValueError(f"Length-{L} read multisets differ — infinite coverage CAN distinguish these pairs at L={L}")

    max_check = min(len(s) for s in haps_a + haps_b)
    crit_L = -1
    for test_L in range(L + 1, max_check + 1):
        if kmer_counts(haps_a, test_L) != kmer_counts(haps_b, test_L):
            crit_L = test_L
            break

    lengths_differ = sorted(len(s) for s in haps_a) != sorted(len(s) for s in haps_b)
    return {
        "valid": True,
        "read_length_L": L,
        "total_L_mers": sum(spec_a.values()),
        "distinct_L_mers": len(spec_a),
        "critical_disambiguation_read_length": crit_L if crit_L != -1 else f">{max_check}",
        "copy_number_or_length_alteration": lengths_differ,
    }


def desk_request(body: dict) -> dict:
    req = urllib.request.Request(
        DEFAULT_DESK_URL,
        data=json.dumps(body).encode("utf-8"),
        headers={"Content-Type": "application/json", "User-Agent": "alzh-unsolved-client/1.0"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=15) as resp:
        return json.loads(resp.read().decode("utf-8"))


def run_desk_cli(cmd: str, argv: List[str]) -> None:
    p = argparse.ArgumentParser(prog=f"verify.py {cmd}")
    if cmd == "desk-claim":
        p.add_argument("--handle", required=True)
        p.add_argument("--agent", default="Coding Agent")
        p.add_argument("--problem", default="auto")
        p.add_argument("--mode", default="all")
        p.add_argument("--focus", default="")
        args = p.parse_args(argv)
        res = desk_request({
            "action": "claim",
            "handle": args.handle,
            "agent": args.agent,
            "problemId": args.problem,
            "mode": args.mode,
            "focus": args.focus,
        })
    elif cmd == "desk-beat":
        p.add_argument("--lease", required=True)
        args = p.parse_args(argv)
        res = desk_request({"action": "beat", "leaseId": args.lease})
    elif cmd == "desk-note":
        p.add_argument("--problem", required=True)
        p.add_argument("--handle", required=True)
        p.add_argument("--agent", default="Coding Agent")
        p.add_argument("--summary", required=True)
        args = p.parse_args(argv)
        res = desk_request({
            "action": "note",
            "problemId": args.problem,
            "handle": args.handle,
            "agent": args.agent,
            "summary": args.summary,
        })
    elif cmd == "desk-negative":
        p.add_argument("--problem", required=True)
        p.add_argument("--handle", required=True)
        p.add_argument("--agent", default="Coding Agent")
        p.add_argument("--reason", default="bound_tight_small_n")
        p.add_argument("--summary", required=True)
        args = p.parse_args(argv)
        res = desk_request({
            "action": "dead_end",
            "problemId": args.problem,
            "handle": args.handle,
            "agent": args.agent,
            "reasonTag": args.reason,
            "summary": args.summary,
        })
    elif cmd == "desk-release":
        p.add_argument("--lease", required=True)
        p.add_argument("--note", default="")
        args = p.parse_args(argv)
        res = desk_request({"action": "release", "leaseId": args.lease, "note": args.note})
    else:
        raise SystemExit(f"Unknown desk subcommand: {cmd}")
    print(json.dumps(res, indent=2))


def run_self_test() -> None:
    n = 8
    c8_edges = [[i, (i + 1) % n] for i in range(n)]
    c8_theta = [2.0 * math.pi * i / n for i in range(n)]
    res_k = verify_kuramoto({"n": n, "edges": c8_edges, "theta": c8_theta})
    assert res_k["valid"] and not res_k["beats_2026_record_0_6838"]

    res_m = verify_minimizer({"sigma": 2, "w": 3, "k": 2, "rank_order": [0, 3, 1, 2]})
    assert res_m["valid"] and 0.25 <= res_m["exact_density"] <= 0.6

    res_d = verify_deletion_code({"n": 5, "t": 2, "codewords": ["AAAAA", "CCCCC", "GGGGG", "TTTTT", "AACCG"]})
    assert res_d["valid"] and res_d["codebook_size"] == 5

    res_u = verify_uhs({"sigma": 2, "k": 3, "w": 5, "kmers": ["000", "010", "011", "111"]})
    assert res_u["valid"]

    res_a = verify_arg_certificate({
        "haplotypes": ["00", "01", "10", "11"],
        "events": [
            {"type": "mut", "parent": "00", "col": 0, "seq": "10"},
            {"type": "mut", "parent": "00", "col": 1, "seq": "01"},
            {"type": "recomb", "left_parent": "10", "right_parent": "01", "breakpoint": 1, "seq": "11"},
        ],
    })
    assert res_a["valid"] and res_a["recombinations_used"] == 1

    res_t = verify_transposition_sorting({
        "permutation": list(range(18, 0, -1)),
        "moves": [[5, 7, 15], [0, 1, 2], [4, 6, 14], [3, 5, 13], [2, 4, 12], [0, 3, 11], [1, 10, 18], [0, 8, 10], [1, 9, 11], [2, 10, 12]],
    })
    assert res_t["valid"] and res_t["moves_used"] == 10 and res_t["bp_odd_cycle_lower_bound"] == 9

    res_dp = verify_diploid_phasing({
        "read_length": 7,
        "haplotypes_a": ["TACGTACAACGTACCACGTACG", "GACGTACT"],
        "haplotypes_b": ["TACGTACAACGTACG", "GACGTACCACGTACT"],
    })
    assert res_dp["valid"] and res_dp["critical_disambiguation_read_length"] == 8
    print("SELF-TEST PASSED: all 7 constructive verifiers operational.")


def main() -> None:
    if len(sys.argv) == 2 and sys.argv[1] == "--self-test":
        run_self_test()
        return
    if len(sys.argv) >= 2 and sys.argv[1].startswith("desk-"):
        run_desk_cli(sys.argv[1], sys.argv[2:])
        return
    if len(sys.argv) != 3:
        print(__doc__.strip(), file=sys.stderr)
        sys.exit(2)
    task, path = sys.argv[1], sys.argv[2]
    data = json.load(open(path, "r", encoding="utf-8"))
    dispatch = {
        "kuramoto": verify_kuramoto,
        "minimizer": verify_minimizer,
        "deletion_code": verify_deletion_code,
        "uhs": verify_uhs,
        "arg_certificate": verify_arg_certificate,
        "transposition_sorting": verify_transposition_sorting,
        "diploid_phasing": verify_diploid_phasing,
    }
    if task not in dispatch:
        raise SystemExit(f"Unknown task {task!r}. Choose from: {', '.join(dispatch)}")
    result = dispatch[task](data)
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
