"""Check one SWV07 schedule locally. Usage: python3 verify.py --example | evidence.json"""
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import tempfile


HERE = Path(__file__).resolve().parent
DATA_SHA = "4e7a285ad4b368cb8b0bb375811591f3bb5e054f665532c84c47d5ec221f4999"
TOOLCHAIN = "leanprover--lean4---v4.36.0"
LEAN_COMMIT = "611c117bfaf7b7ae1cfcf246ce6fba31e8f509e9"
LIMIT = 1593


def read_instance():
    raw = (HERE / "swv07.json").read_bytes()
    if hashlib.sha256(raw).hexdigest() != DATA_SHA:
        raise ValueError("The instance differs from the pinned release.")
    return json.loads(raw)


def inspect(jobs, starts):
    if type(starts) is not list or len(starts) != len(jobs):
        raise ValueError("The schedule must have 20 rows in job order.")
    machines = [[] for _ in range(15)]
    first = []
    finish = 0
    for j, (job, row) in enumerate(zip(jobs, starts)):
        if type(row) is not list or len(row) != len(job):
            raise ValueError(f"Job {j} needs 15 start times.")
        ready = 0
        for (machine, duration), start in zip(job, row):
            if type(start) is not int or not 0 <= start <= 100000:
                raise ValueError("Use whole start times from 0 through 100000.")
            if start < ready:
                raise ValueError(f"Job {j} starts its next operation too early.")
            ready = start + duration
            machines[machine].append((start, ready))
            if machine == 0 and j < 3:
                first.append((start, j))
        finish = max(finish, ready)
    for m, intervals in enumerate(machines):
        intervals.sort()
        if any(b[0] < a[1] for a, b in zip(intervals, intervals[1:])):
            raise ValueError(f"Machine {m} has overlapping operations.")
    return finish, min(first)[1]


def lean_statement(jobs, starts, finish):
    def render(rows, convert):
        return "[" + ",\n".join("[" + ",".join(map(convert, row)) + "]" for row in rows) + "]"
    data = render(jobs, lambda p: f"({p[0]},{p[1]})")
    times = render(starts, str)
    source = (HERE / "Swv07.lean").read_text()
    source += f"\nset_option maxRecDepth 50000\nset_option maxHeartbeats 5000000\n"
    source += f"def swv07 : List (List (Nat × Nat)) := {data}\ndef starts : List (List Nat) := {times}\n"
    source += f"theorem scheduleFits : MoonPrize.fits swv07 starts {finish} = true := by decide\n"
    if finish <= LIMIT:
        source += f"theorem improvesBound : MoonPrize.fits swv07 starts {LIMIT} = true := by decide\n"
    return source + "#print axioms scheduleFits\n"


def verify(payload, data):
    starts = payload.get("starts") if type(payload) is dict and set(payload) == {"starts"} else None
    # JSON permits integral numbers such as 1.0. Normalize them as the browser does.
    if isinstance(starts, list):
        starts = [[int(t) if type(t) is float and t.is_integer() and 0 <= t <= 100000 else t
                   for t in row] if isinstance(row, list) else row for row in starts]
    finish, branch = inspect(data["jobs"], starts)
    lean = Path.home() / ".elan" / "toolchains" / TOOLCHAIN / "bin" / "lean"
    if not lean.is_file() or subprocess.check_output([str(lean), "-g"], text=True, timeout=8).strip() != LEAN_COMMIT:
        return {"state": "unavailable", "message": "Install the pinned Lean 4.36.0 toolchain and run the check again."}
    with tempfile.TemporaryDirectory(prefix="moonprize-lean-") as tmp:
        path = Path(tmp) / "Certificate.lean"
        path.write_text(lean_statement(data["jobs"], starts, finish))
        proc = subprocess.run([str(lean), "-j1", "-M1024", path.name], cwd=tmp, capture_output=True, text=True, timeout=35)
    if proc.returncode or "does not depend on any axioms" not in proc.stdout:
        return {"state": "unavailable", "message": "Lean could not certify this schedule. Leave the claim pending."}
    improves = finish <= LIMIT
    message = f"Lean verified all 300 operations finish by {finish}. "
    message += "This improves the pinned upper bound of 1594. Recheck the live record before claiming priority." if improves else "The search target is 1593 or less."
    return {"state": "improves" if improves else "feasible", "makespan": finish, "branch": branch, "message": message}


def main():
    data = read_instance()
    if sys.argv[1:] == ["--example"]:
        payload = {"starts": data["exampleStarts"]}
    elif sys.argv[1:] == ["--stdin"]:
        payload = json.loads(sys.stdin.buffer.read(8001))
    elif len(sys.argv) == 2 and Path(sys.argv[1]).stat().st_size <= 8000:
        payload = json.loads(Path(sys.argv[1]).read_bytes())
    else:
        raise ValueError("Supply a single evidence JSON file (up to 8000 bytes) or --example.")
    return verify(payload, data)


if __name__ == "__main__":
    try:
        result = main()
    except (ValueError, RecursionError) as error:
        result = {"state": "invalid", "message": str(error)}
    except (OSError, subprocess.SubprocessError):
        result = {"state": "unavailable", "message": "The pinned checker could not finish on this computer."}
    print(json.dumps(result))
    sys.exit(0 if result["state"] in ("improves", "feasible") else 1)
