#!/usr/bin/env python3
"""Check a SAT solver written by an agent, independently of the agent.

Standard library only. Subcommands:

  run SOLVER.py   run the solver on fresh random 3-CNF formulas it has never
                  seen; verify every satisfying assignment; verify every UNSAT
                  answer by its DRAT proof (--proofs) or against a reference
                  DPLL solver
  drat F.cnf P    check a DRAT proof (RUP steps only) of unsatisfiability
  scan PATH       list lines that may be shortcuts: other solvers, processes,
                  non-standard imports, the bench answers, file names

The solver is expected to follow TASK.md of the starter repository:
  python3 solver.py F.cnf [--proof P.drat]
prints "s SATISFIABLE" with "v ... 0" lines, or "s UNSATISFIABLE".
"""

import argparse
import os
import random
import re
import subprocess
import sys
import tempfile
import time
from pathlib import Path


# ---------------------------------------------------------------- formulas

def random_3cnf(n, m, rng):
    """Uniform random 3-CNF: three distinct variables per clause, random signs."""
    return [tuple(v if rng.random() < 0.5 else -v for v in rng.sample(range(1, n + 1), 3))
            for _ in range(m)]


def write_dimacs(path, n, clauses, comment=None):
    lines = [f"c {comment}"] if comment else []
    lines.append(f"p cnf {n} {len(clauses)}")
    lines += [" ".join(map(str, c)) + " 0" for c in clauses]
    Path(path).write_text("\n".join(lines) + "\n")


def read_dimacs(path):
    n, clauses, current = 0, [], []
    for line in Path(path).read_text().splitlines():
        line = line.strip()
        if not line or line[0] in "c%":
            continue
        if line.startswith("p"):
            n = int(line.split()[2])
            continue
        for tok in line.split():
            lit = int(tok)
            if lit == 0:
                clauses.append(tuple(current))
                current = []
            else:
                current.append(lit)
    return n, clauses


# ------------------------------------------------------- reference solver

def _assign(clauses, lit):
    """Clauses after setting lit true; None if a clause becomes empty."""
    out = []
    for c in clauses:
        if lit in c:
            continue
        if -lit in c:
            c = tuple(x for x in c if x != -lit)
            if not c:
                return None
        out.append(c)
    return out


def _propagate(clauses, trail):
    while True:
        unit = next((c[0] for c in clauses if len(c) == 1), None)
        if unit is None:
            return clauses
        trail.append(unit)
        clauses = _assign(clauses, unit)
        if clauses is None:
            return None


def _choose(clauses):
    """Most occurrences in the shortest clauses; the more frequent sign first."""
    k = min(len(c) for c in clauses)
    count = {}
    for c in clauses:
        if len(c) == k:
            for lit in c:
                count[lit] = count.get(lit, 0) + 1
    var = max({abs(l) for l in count},
              key=lambda v: count.get(v, 0) * count.get(-v, 0) * 1024 + count.get(v, 0) + count.get(-v, 0))
    return var if count.get(var, 0) >= count.get(-var, 0) else -var


def reference_solve(clauses):
    """Plain DPLL. Returns a set of true literals, or None if unsatisfiable.

    Deliberately simple, so that it can be read in a few minutes; fast enough
    for random 3-CNF with up to about 100 variables.
    """
    def solve(cls, trail):
        cls = _propagate(cls, trail)
        if cls is None:
            return None
        if not cls:
            return trail
        lit = _choose(cls)
        for choice in (lit, -lit):
            reduced = _assign(cls, choice)
            if reduced is not None:
                found = solve(reduced, trail + [choice])
                if found is not None:
                    return found
        return None

    found = solve(list(clauses), [])
    return None if found is None else set(found)


# ------------------------------------------------------------ model check

def check_model(n, clauses, true_lits):
    """None if the assignment satisfies every clause, else the reason."""
    for lit in true_lits:
        if not 1 <= abs(lit) <= n:
            return f"literal {lit} is outside 1..{n}"
        if -lit in true_lits:
            return f"variable {abs(lit)} is both true and false"
    for i, c in enumerate(clauses):
        if not any(lit in true_lits for lit in c):
            return f"clause {i + 1} ({' '.join(map(str, c))}) is false"
    return None


# ------------------------------------------------------------- DRAT check

def check_drat(n, clauses, proof_text):
    """Forward check of a DRAT proof whose lemmas are all RUP.

    Every lemma must follow by unit propagation from the formula and the
    earlier lemmas, and the proof must derive the empty clause. Deletions of
    non-unit clauses are honoured; ignoring a deletion is always sound.
    RAT lemmas are reported as failures (a plain CDCL solver produces none).
    Returns (ok, message).
    """
    val = [0] * (n + 1)                   # 1 true, -1 false, 0 unassigned
    watches = {}                          # literal -> clause ids watching it
    db, units, alive = [], [], []
    index = {}                            # sorted clause -> ids, for deletions

    def value(lit):
        v = val[abs(lit)]
        return v if lit > 0 else -v

    def add(c):
        c = list(dict.fromkeys(c))
        if any(-l in c for l in c):       # tautology: harmless, skip
            return
        cid = len(db)
        db.append(c)
        alive.append(True)
        index.setdefault(tuple(sorted(c)), []).append(cid)
        if len(c) == 1:
            units.append(cid)
        elif c:
            for lit in c[:2]:
                watches.setdefault(lit, []).append(cid)

    def rup(lemma):
        """True if assigning the negation of lemma propagates to a conflict."""
        trail = []

        def set_true(lit):
            v = value(lit)
            if v == 1:
                return True
            if v == -1:
                return False
            val[abs(lit)] = 1 if lit > 0 else -1
            trail.append(lit)
            return True

        try:
            for cid in units:
                if alive[cid] and not set_true(db[cid][0]):
                    return True
            for lit in lemma:
                if not set_true(-lit):
                    return True
            head = 0
            while head < len(trail):
                false_lit = -trail[head]
                head += 1
                ws = watches.get(false_lit, [])
                i = 0
                while i < len(ws):
                    cid = ws[i]
                    c = db[cid]
                    if not alive[cid]:
                        ws[i] = ws[-1]; ws.pop()
                        continue
                    if c[0] == false_lit:
                        c[0], c[1] = c[1], c[0]
                    if value(c[0]) == 1:
                        i += 1
                        continue
                    for k in range(2, len(c)):
                        if value(c[k]) != -1:
                            c[1], c[k] = c[k], c[1]
                            watches.setdefault(c[1], []).append(cid)
                            ws[i] = ws[-1]; ws.pop()
                            break
                    else:
                        if not set_true(c[0]):
                            return True
                        i += 1
            return False
        finally:
            for lit in trail:
                val[abs(lit)] = 0

    for c in clauses:
        add(c)
    steps = 0
    for line_no, line in enumerate(proof_text.splitlines(), 1):
        toks = line.split()
        if not toks or toks[0] == "c":
            continue
        delete = toks[0] == "d"
        try:
            lits = [int(t) for t in toks[1:] if t] if delete else [int(t) for t in toks]
        except ValueError:
            return False, f"line {line_no}: not a DRAT line: {line!r}"
        if not lits or lits[-1] != 0:
            return False, f"line {line_no}: missing the final 0"
        lits = lits[:-1]
        if any(abs(l) > n for l in lits):
            return False, f"line {line_no}: variable outside 1..{n}"
        if delete:
            ids = index.get(tuple(sorted(dict.fromkeys(lits))), [])
            live = [cid for cid in ids if alive[cid]]
            if live and len(lits) > 1:
                alive[live[-1]] = False
            continue
        steps += 1
        if not rup(lits):
            return False, f"line {line_no}: lemma {' '.join(map(str, lits))} 0 is not RUP"
        if not lits:
            return True, f"empty clause derived after {steps} lemmas"
        add(lits)
    if rup([]):
        return True, f"conflict by unit propagation after {steps} lemmas"
    return False, f"no empty clause after {steps} lemmas"


# ------------------------------------------------------------- run solver

def run_solver(solver, cnf, timeout, proof=None):
    cmd = [sys.executable, str(solver), str(cnf)] + (["--proof", str(proof)] if proof else [])
    start = time.monotonic()
    try:
        out = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
    except subprocess.TimeoutExpired:
        return "TIMEOUT", None, timeout
    elapsed = time.monotonic() - start
    status, lits = None, set()
    for line in out.stdout.splitlines():
        if line.startswith("s "):
            status = line[2:].strip()
        elif line.startswith("v "):
            lits.update(int(t) for t in line[2:].split() if t != "0")
    if status not in ("SATISFIABLE", "UNSATISFIABLE"):
        tail = (out.stderr or out.stdout).strip().splitlines()[-1:] or ["no output"]
        return "ERROR", tail[0][:120], elapsed
    return status, lits, elapsed


def cmd_run(args):
    solver = Path(args.solver).resolve()
    seed = args.seed if args.seed is not None else int(time.time())
    rng = random.Random(seed)
    print(f"Solver: {solver}")
    print(f"Fresh formulas: seed {seed}, {args.count} per size, sizes {args.n}, "
          f"clauses = round({args.ratio} n), timeout {args.timeout} s")
    totals = {"sat ok": 0, "unsat proved": 0, "unsat agrees": 0, "WRONG": 0,
              "TIMEOUT": 0, "ERROR": 0, "proof failed": 0}
    with tempfile.TemporaryDirectory() as tmp:
        for n in args.n:
            m = round(args.ratio * n)
            times = []
            for i in range(args.count):
                clauses = random_3cnf(n, m, rng)
                cnf = Path(tmp) / f"f{n}_{i:03d}.cnf"
                write_dimacs(cnf, n, clauses)
                proof = Path(tmp) / f"f{n}_{i:03d}.drat" if args.proofs else None
                status, lits, elapsed = run_solver(solver, cnf, args.timeout, proof)
                times.append(elapsed)
                verdict, note = check_answer(n, clauses, status, lits, proof)
                totals[verdict] += 1
                if verdict in ("WRONG", "ERROR", "proof failed") or args.verbose:
                    print(f"  n={n} #{i:03d}: {status} -> {verdict}{': ' + note if note else ''}")
            print(f"n = {n:3d}: {args.count} formulas, mean {sum(times) / len(times):.2f} s, "
                  f"max {max(times):.2f} s")
    print()
    for key, value in totals.items():
        print(f"{key:>14}: {value}")
    bad = totals["WRONG"] + totals["proof failed"]
    print("\nVERDICT:", "no wrong answers found" if not bad else f"{bad} wrong answers or proofs")
    return 1 if bad else 0


def check_answer(n, clauses, status, lits, proof):
    if status in ("TIMEOUT", "ERROR"):
        return status, lits if status == "ERROR" else None
    if status == "SATISFIABLE":
        problem = check_model(n, clauses, lits)
        return ("WRONG", problem) if problem else ("sat ok", None)
    if proof is not None and proof.exists():
        ok, message = check_drat(n, clauses, proof.read_text())
        if ok:
            return "unsat proved", message
        if reference_solve(clauses) is not None:
            return "WRONG", "satisfiable according to the reference"
        return "proof failed", message
    if reference_solve(clauses) is not None:
        return "WRONG", "satisfiable according to the reference"
    return "unsat agrees", None


# ------------------------------------------------------------------- scan

SOLVER_NAMES = r"pysat|pycosat|minisat|glucose|cadical|kissat|lingeling|cryptominisat|picosat|z3|ortools|cvc5|sympy"
SUSPICIOUS = [
    (re.compile(r"\b(" + SOLVER_NAMES + r")\b", re.I), "another solver"),
    (re.compile(r"\b(subprocess|os\.system|os\.popen|os\.exec\w*|ctypes|cffi)\b"), "runs other programs or native code"),
    (re.compile(r"answers?\.csv|\bexpected\b", re.I), "reads expected answers"),
    (re.compile(r"\bbasename\b|\.name\b|\.stem\b|\buuf|\bunsat\w*\s+in\b", re.I), "may depend on the file name"),
    (re.compile(r"\b(urllib|requests|http\.client|socket)\b"), "network access"),
]


def cmd_scan(args):
    root = Path(args.path)
    files = [root] if root.is_file() else sorted(p for p in root.rglob("*.py") if ".git" not in p.parts)
    stdlib = getattr(sys, "stdlib_module_names", set())
    local = {p.stem for p in files}
    found = 0
    for path in files:
        for no, line in enumerate(path.read_text(errors="replace").splitlines(), 1):
            reasons = [why for rx, why in SUSPICIOUS if rx.search(line)]
            m = re.match(r"\s*(?:from\s+([\w.]+)\s+import|import\s+([\w., ]+))", line)
            if m:
                mods = [m.group(1)] if m.group(1) else [part.split()[0] for part in m.group(2).split(",") if part.split()]
                for mod in mods:
                    top = mod.split(".")[0]
                    if stdlib and top not in stdlib and top not in local:
                        reasons.append(f"non-standard module {top}")
            if reasons:
                found += 1
                print(f"{path}:{no}: {line.strip()[:100]}\n    -> {', '.join(dict.fromkeys(reasons))}")
    print(f"\n{found} lines to read by hand in {len(files)} files." if found else
          f"Nothing suspicious in {len(files)} files. (A scan is not a proof: read the solver's main loop.)")
    return 0


def cmd_drat(args):
    n, clauses = read_dimacs(args.cnf)
    ok, message = check_drat(n, clauses, Path(args.proof).read_text())
    print(("VERIFIED: " if ok else "NOT VERIFIED: ") + message)
    return 0 if ok else 1


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = parser.add_subparsers(dest="command", required=True)
    run = sub.add_parser("run", help="run the solver on fresh formulas and check every answer")
    run.add_argument("solver")
    run.add_argument("--n", type=int, nargs="+", default=[50, 75, 100])
    run.add_argument("--count", type=int, default=20, help="formulas per size")
    run.add_argument("--ratio", type=float, default=4.26)
    run.add_argument("--seed", type=int)
    run.add_argument("--timeout", type=float, default=60)
    run.add_argument("--proofs", action="store_true", help="ask for DRAT proofs and check them")
    run.add_argument("--verbose", action="store_true")
    drat = sub.add_parser("drat", help="check a DRAT proof")
    drat.add_argument("cnf")
    drat.add_argument("proof")
    scan = sub.add_parser("scan", help="list lines that may be shortcuts")
    scan.add_argument("path")
    args = parser.parse_args()
    return {"run": cmd_run, "drat": cmd_drat, "scan": cmd_scan}[args.command](args)


if __name__ == "__main__":
    sys.exit(main())
