"""Independent exact upper-bound checks for the P85 Hosono review.

Standard library only. No imports from the author's code. Input: the pinned
square-packing checkout, including its n6/n37 upper certificates and controls.
This checks constructions, NOT lower bounds or optimality.
"""
import argparse
from dataclasses import dataclass
from fractions import Fraction as F
import hashlib
import json
from pathlib import Path


@dataclass(frozen=True)
class Q:
    a: F = F(0)
    b: F = F(0)

    def __post_init__(self):
        object.__setattr__(self, 'a', F(self.a))
        object.__setattr__(self, 'b', F(self.b))

    def __add__(self, other):
        o = other if isinstance(other, Q) else Q(other)
        return Q(self.a + o.a, self.b + o.b)

    __radd__ = __add__

    def __neg__(self):
        return Q(-self.a, -self.b)

    def __sub__(self, other):
        return self + -other

    def __mul__(self, other):
        o = other if isinstance(other, Q) else Q(other)
        return Q(self.a * o.a + 3 * self.b * o.b, self.a * o.b + self.b * o.a)

    __rmul__ = __mul__

    def sign(self):
        a, b = self.a, self.b
        if b == 0:
            return (a > 0) - (a < 0)
        if a == 0 or (a > 0) == (b > 0):
            return 1 if b > 0 else -1
        # Opposite signs: compare rational squares, never approximate sqrt(3).
        t = a * a - 3 * b * b
        return ((t > 0) - (t < 0)) * (1 if a > 0 else -1)

    def __lt__(self, other):
        return (self - other).sign() < 0


ZERO, ONE, ROOT3 = Q(), Q(1), Q(0, 1)


def sub(p, q):
    return p[0] - q[0], p[1] - q[1]


def dot(p, q):
    return p[0] * q[0] + p[1] * q[1]


def check(side, squares, n):
    assert side.sign() > 0 and len(squares) == n
    for i, square in enumerate(squares):
        assert len(square) == 4, ('vertices', i)
        edges = [sub(square[(k + 1) % 4], square[k]) for k in range(4)]
        for k, edge in enumerate(edges):
            assert dot(edge, edge) == ONE, ('unit edge', i, k)
            assert dot(edge, edges[(k + 1) % 4]) == ZERO, ('right angle', i, k)
        assert edges[0] == tuple(-v for v in edges[2]), ('opposite edges', i)
        assert edges[1] == tuple(-v for v in edges[3]), ('opposite edges', i)
        for x, y in square:
            assert y.sign() >= 0 and (ROOT3 * x - y).sign() >= 0 and (ROOT3 * (side - x) - y).sign() >= 0, ('containment', i)
    for i, first in enumerate(squares):
        for j in range(i):
            second = squares[j]
            axes = [sub(s[1], s[0]) for s in (first, second)] + [sub(s[2], s[1]) for s in (first, second)]
            separated = False
            for axis in axes:
                a, b = [dot(p, axis) for p in first], [dot(p, axis) for p in second]
                # Equality is allowed: touching boundaries, disjoint interiors.
                if (min(b) - max(a)).sign() >= 0 or (min(a) - max(b)).sign() >= 0:
                    separated = True
                    break
            assert separated, ('overlap', i, j)


def rectangle(x, y):
    return [(x, y), (x + ONE, y), (x + ONE, y + ONE), (x, y + ONE)]


def pinwheel3():
    # Centres/cosines/sines from the cited Lean Main.sq3; verified here directly.
    poses = [(Q('1/2', '1/3'), Q('1/2'), ONE, ZERO),
             (Q('5/4', '7/12'), Q('1/4', '1/4'), Q(0, '1/2'), Q('1/2')),
             (Q('1/2', '7/12'), Q('3/4', '1/2'), Q('1/2'), Q(0, '1/2'))]
    return [[(x + (c * a - s * b) * F(1, 2), y + (s * a + c * b) * F(1, 2))
             for a, b in [(-1, -1), (1, -1), (1, 1), (-1, 1)]] for x, y, c, s in poses]


def load(path):
    data = json.loads(path.read_text(encoding='utf-8'))
    return Q(*data['container']['side']), [[tuple(Q(*v) for v in p) for p in s] for s in data['squares']]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('source', type=Path)
    parser.add_argument('output', type=Path)
    args = parser.parse_args()
    result = {'arithmetic': 'exact Fraction arithmetic in Q(sqrt(3)); no tolerance', 'upper': [], 'negativeControls': []}
    cases = {3: (Q('3/2', 1), pinwheel3())}
    for m, counts in [(3, [3, 1]), (4, [4, 2, 1]), (5, [5, 3, 2, 1]),
                      (6, [6, 4, 3, 2, 1]), (7, [7, 5, 4, 3, 2, 1]), (8, [8, 6, 5, 4, 3, 2, 1])]:
        cases[sum(counts)] = (Q(m, '2/3'), [rectangle(Q(i, F(j + 1, 3)), Q(j)) for j, count in enumerate(counts) for i in range(count)])
    certs = args.source / 'problems/triangle/certificates'
    for n, name in [(6, 'packing.json'), (37, 'n37_packing.json')]:
        folder = certs / f'n{n}/upper'
        cases[n] = load(folder / name)
        for path in sorted(folder.glob('neg*.json')):
            try:
                check(*load(path), n)
            except AssertionError as error:
                result['negativeControls'].append({'file': str(path.relative_to(args.source)).replace('\\', '/'), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest(), 'rejected': True, 'reason': str(error)})
            else:
                raise AssertionError(('negative control accepted', str(path)))
    for n, (side, squares) in sorted(cases.items()):
        check(side, squares, n)
        result['upper'].append({'n': n, 'side': [str(side.a), str(side.b)], 'unitSquares': n, 'pairsChecked': n * (n - 1) // 2, 'verified': True})
    assert len(result['negativeControls']) == 9
    args.output.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
    print('PASS: 9 exact upper constructions; 9 deliberately invalid constructions rejected')


if __name__ == '__main__':
    main()
