"""Synthesize a strip measurement using model predictions and public apparatus rules only."""
import json
import sys
from collections import Counter
from itertools import combinations, combinations_with_replacement, product
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "rival-one-case"))
from discover import tree, value


def travel(path):
    return sum(abs(step) for step in path)


def crossings(path):
    visits = Counter()
    position = 0
    for move in path:
        end = position + move
        visits.update(range(min(position, end), max(position, end)))
        position = end
    return visits


def local_levels(display, visits):
    """Derive mark levels from paths on which all touched cells have the same visit count."""
    levels = {0: 0}
    witnesses = {}
    for path in sorted(visits, key=lambda p: (travel(p), p)):
        counts = set(visits[path].values())
        if len(counts) != 1:
            continue
        count = next(iter(counts))
        if count in levels:
            continue
        level, remainder = divmod(display[path], len(visits[path]))
        if remainder or level < 0:
            raise ValueError("A uniform nonnegative integer mark level cannot explain this path")
        levels[count] = level
        witnesses[count] = {"path": path, "display": display[path],
                            "equally_exposed_cells": len(visits[path])}
    for path, cells in visits.items():
        if sum(levels[count] for count in cells.values()) != display[path]:
            raise ValueError("The shared local measurement assumptions do not reproduce the model")
    return levels, witnesses


def expressions(cuts):
    # Terms are (coefficient, shutter edge). Report the nonnegative orientation
    # of a difference; swapping its sign describes the same measurement.
    for edge in cuts:
        yield ((1, edge),)
    for left, right in combinations_with_replacement(cuts, 2):
        yield ((1, right), (1, left))
        yield ((1, right), (-1, left))


def design(packet):
    paths = list(product(*packet["move_levels"]))
    visits = {p: crossings(p) for p in paths}
    excluded = {tuple(p) for p in packet["previously_read_paths"]}
    fresh = [p for p in paths if p not in excluded]
    cuts = packet["shutter_edges"]
    displays, shutters, calibrations = {}, {}, {}
    for name, formula in packet["fixed_formulas"].items():
        expr = tree(formula)
        displays[name] = {p: value(expr, dict(zip(("a", "b"), p))) for p in paths}
        levels, witnesses = local_levels(displays[name], visits)
        calibrations[name] = {"mark_level_by_visits": levels, "derivation_witnesses": witnesses,
                              "paths_checked_against_original_formula": len(paths)}
        # No actual cell image or scanner readings are input to the design.
        shutters[name] = {
            p: {edge: sum(levels[n] for cell, n in visits[p].items() if cell < edge)
                for edge in cuts} for p in paths
        }
    pairs = [(p, q) for p, q in combinations(fresh, 2) if sum(p) == sum(q)
             and all(d[p] == d[q] for d in displays.values())]
    counts = Counter()
    best = best_key = None
    for terms in expressions(cuts):
        counts["expressions_generated"] += 1
        if sum(coef for coef, edge in terms):
            counts["depends_on_unknown_scanner_zero"] += 1
            continue
        counts["invariant_to_scanner_zero"] += 1
        for p, q in pairs:
            counts["invariant_expression_path_pairs"] += 1
            predictions = {
                name: [sum(coef * table[path][edge] for coef, edge in terms) for path in (p, q)]
                for name, table in shutters.items()
            }
            contrasts = [first - second for first, second in predictions.values()]
            if len(set(contrasts)) == 1:
                continue
            counts["distinct_model_contrasts"] += 1
            edges = sorted(edge for coef, edge in terms)
            margin = max(contrasts) - min(contrasts)
            key = (len(terms), travel(p) + travel(q), edges[-1] - edges[0], -margin,
                   p, q, edges)
            if best_key is None or key < best_key:
                best_key = key
                best = {"paths": [p, q], "signed_endpoints": [sum(p), sum(q)],
                        "old_display_predictions": {name: [d[p], d[q]] for name, d in displays.items()},
                        "terms": [{"coefficient": c, "edge": edge} for c, edge in terms],
                        "shutter_read_order": edges, "new_measurement_predictions": predictions,
                        "predicted_first_minus_second": dict(zip(predictions, contrasts))}
    return {"local_predictions_derived_from_fixed_formulas": calibrations,
            "previously_unmeasured_paths": len(fresh), "eligible_matched_pairs": pairs,
            "search_counts": dict(counts), "proposal": best}


if __name__ == "__main__":
    print(json.dumps(design(json.load(sys.stdin)), indent=2))
