"""The leading coefficient of cost-constrained signed joins of the catalogue."""
from math import comb
from pathlib import Path
import re
import sys
import unittest

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'proofs'))


class CatalogueCancellation(unittest.TestCase):
    def test_atomic_certificates_cover_the_published_sequences(self):
        # Replicata: recover the actual order-u coefficient from every near-unit code.
        # Expectata: each is a unit modulo three and every fast atom has the cubic root.
        # Resultata before: the catalogue rate bound only handled the stated join rule.
        from catalogue_cancellation import atoms, check
        from pow2rate import chart
        data = chart('mstar')
        rows = dict(enumerate(data['cols'],1)) | {n: row for n,*row in data['past']}
        codes = {(n,rows[n][0]): h for n,h,_ in data['examples']}
        codes.update({(int(n),int(u)):h for n,u,h in re.findall(
            r'<code id="(\d+):(\d+)">([A-F0-9]+)</code>', (ROOT/'index.html').read_text())})
        # The cubic-edge examples add two order-16 polynomials to the catalogue.
        self.assertEqual(check(), {2192: 2, 2224: 1, 19712: 1, 19744: 1})
        for n,u in atoms():
            if n % 3 and n**15 < 7360**(u+1):
                h = codes[n,u]
                a = [2*int(b)-1 for b in f'{int(h,16):0{4*len(h)}b}'[:n//2]]
                a += [(-1)**u*x for x in a[::-1]]
                self.assertEqual(len(a),n)
                self.assertNotEqual(sum(x*comb(i,u) for i,x in enumerate(a))%3,0)
            if n**15 < 7360**u:
                self.assertEqual(n%3,0)
                # The cubic root condition reduces to equality of the three residue sums.
                h = codes[n,u]
                a = [2*int(b)-1 for b in f'{int(h,16):0{4*len(h)}b}'[:n//2]]
                a += [(-1)**u*x for x in a[::-1]]
                self.assertEqual([sum(a[r::3]) for r in range(3)],[0]*3)

    def test_signed_leading_coefficient_and_a_real_cancellation(self):
        from pow2rate import chart
        from symcenters import coefficients
        from catalogue_cancellation import check
        check()
        codes = {n:h for n,h,_ in chart('mstar')['examples']}
        def decode(n):
            left = [2*int(v)-1 for v in f'{int(codes[n],16):0{n//2}b}']
            return left + [-x for x in left[::-1]]
        unit, fast = map(decode,(7360,1728))
        for sign in (-1,1):
            for order in ((unit,[sign*x for x in fast]),([sign*x for x in fast],unit)):
                jet=coefficients(order[0]+order[1],16)
                self.assertEqual(jet[:15],[0]*15)
                self.assertNotEqual(jet[15]%3,0)
        # Two unit copies can lift order by one just beyond the theorem's length range.
        doubled=coefficients(unit+[-x for x in unit],17)
        self.assertEqual(doubled[:16],[0]*16)
        self.assertNotEqual(doubled[16],0)
        self.assertLess((7360+1728)**15,7360**16)
        self.assertGreater((2*7360)**15,7360**16)

    def test_cubic_norm_bound_covers_every_atom_and_download(self):
        # Replicata: reconstruct F(z) by summing the actual signs by residue.
        # Expectata: the bound handles both exceptional nonzero divisible-length projections,
        # and a two-order gain below A^(u+2) permits exactly one positive norm.
        from catalogue_cancellation import projection_norms, atoms
        norms = projection_norms()
        self.assertEqual(set(norms),atoms())
        self.assertEqual(norms[7360,15],{3**15})
        self.assertEqual(norms[530544,15],{4*3**15})
        self.assertEqual(norms[531984,15],{4*3**15})
        self.assertEqual(norms[338784,17],{0})
        self.assertTrue(all(max(V)**15 * 7360**(2*u) <= (n*n*3**u)**15
                            for (n,u),V in norms.items()))
        self.assertTrue(9**15 < 7360**4 < 18**15)
        text=(ROOT/'index.html').read_text()
        self.assertIn('id="catalogue-multilift"',text)
        self.assertIn(r'3^{h/2}',text.split('id="catalogue-multilift"')[1].split('</p>')[0])

    def test_the_signed_proof_links_the_checker_and_examples(self):
        page=(ROOT/'index.html').read_text()
        body,=re.findall(r'<div class="proof-body" id="catalogue-cancellation">(.*?)</div>',page,re.S)
        self.assertTrue(body.strip().startswith('<p>“') and body.strip().endswith('”</p>'))
        self.assertIn('href="#pow2-rate"',body)
        self.assertIn('/proofs/catalogue_cancellation.py"',body)
        self.assertIn('href="#entry-2192"',body)
        self.assertIn('href="#entry-2224"',body)
        self.assertIn('href="#entry-19712"',body)
        self.assertIn('href="#entry-19744"',body)


if __name__ == '__main__':
    unittest.main()
