"""Koldflux brand-colour contrast test. Usage: python3 contrast-test.py <workdir> <tool_json_colors> <tool_json_fixed>
Tests: A formula vs live tool, B nearest passing shade vs tool shade table, C encode and phone-size scaling."""
import sys, os, json, subprocess
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from wcag import *
from measure import read_rgb, core_mask, mean_rgb

here = os.path.dirname(os.path.abspath(__file__))
work = sys.argv[1]; os.makedirs(work, exist_ok=True)
cols = [l.split('\t') for l in open(os.path.join(here, 'colors.tsv')).read().split('\n') if l]
log = []
def P(*a):
    s = ' '.join(str(x) for x in a); print(s); log.append(s)
def sh(cmd):
    r = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if r.returncode: print(r.stderr[-400:]); raise SystemExit('cmd failed: ' + cmd[:80])
    return r

W, B_ = (255, 255, 255), (0, 0, 0)
# ---- controls for the formula
P('CONTROL formula black/white =', '%.2f' % ratio(B_, W), '(expect 21.00); white/white =', '%.2f' % ratio(W, W), '(expect 1.00)')
assert '%.2f' % ratio(B_, W) == '21.00' and '%.2f' % ratio(W, W) == '1.00'

# ---- Test A: script vs tool
tool = {o['input'].upper(): o for o in json.load(open(sys.argv[2]))}
P('\nTEST A: colour on white and on black, script vs live tool (2 decimals)')
P('name\thex\tscript_white\ttool_white\tscript_black\ttool_black\tmatch')
okA = 0; nA = 0
for name, hx in cols + [('control-black', '#000000'), ('control-white', '#FFFFFF')]:
    c = hex_rgb(hx); sw = '%.2f' % ratio(c, W); sb = '%.2f' % ratio(c, B_)
    t = tool[hx.upper()]; m = (sw == t['onWhite'] and sb == t['onBlack'])
    okA += 2 * m; nA += 2
    P(name, hx, sw, t['onWhite'], sb, t['onBlack'], 'OK' if m else 'DIFF')
P('A: %d of %d readings equal' % (okA, nA))

# ---- Test A2: pairs the tool cannot check (neither colour is white or black): script only
P('\nTEST A2: colour on colour (script only, the tool takes one colour)')
navy = '#0B1F3A'
pairs = [('#FFFFFF', '#2563EB'), ('#FFFFFF', '#1BA39C'), ('#FFFFFF', '#E91E63'), (navy, '#FFD600'), (navy, '#8BC34A'), ('#FF6F61', navy), ('#3FA9F5', '#4F46E5'), ('#FFD600', '#F5821F')]
P('text\tbackground\tratio\tAA_normal_4.5\tlarge_or_UI_3')
for a, b in pairs:
    r = ratio(hex_rgb(a), hex_rgb(b)); P(a, b, '%.2f' % r, 'pass' if r >= 4.5 else 'fail', 'pass' if r >= 3 else 'fail')

# ---- Test B: nearest passing colour by mixing with black in 1% steps vs the tool's 10% shade table
P('\nTEST B: text colour on white, nearest passing shade')
shade_ok = 0; shade_n = 0; table_stale = 0
for name, hx in cols:
    c = hex_rgb(hx); t = tool[hx.upper()]
    for i, th in enumerate(t['shades']):
        shade_n += 1; shade_ok += (rgb_hex(mix(c, B_, (i + 1) / 10)) == th)
    table_stale += (t['tableRow1'] is not None and t['tableRow1'].split('\t')[1] == '#1A8D8D')
P('CONTROL mix(): script shade hex equals the tool Shades swatch in %d of %d cells' % (shade_ok, shade_n))
P('NOTE: the tool STEP/TINT/CONTRAST table still showed the default teal row (#1A8D8D) for %d of %d inputs, so it was not used' % (table_stale, len(cols)))
fixed = {}
P('name\thex\tratio_white\tfirst_pass_1pct(4.5)\tfixed_hex\tfixed_ratio\ttool_first_10pct_pass(script ratio)\tfirst_pass_1pct(3.0)\thex3\tmargin_target_%.3f_first_pass' % (4.5 * 1.15))
for name, hx in cols:
    c = hex_rgb(hx); r0 = ratio(c, W)
    def first(th):
        if r0 >= th: return 0, hx
        for k in range(1, 101):
            h2 = rgb_hex(mix(c, B_, k / 100))
            if ratio(hex_rgb(h2), W) >= th: return k, h2
    k45, h45 = first(4.5); k3, h3 = first(3.0); km, hm = first(4.5 * 1.15)
    t = tool[hx.upper()]
    tp = '-' if r0 >= 4.5 else next(('%d%% %s %.2f' % ((i + 1) * 10, s, ratio(hex_rgb(s), W)) for i, s in enumerate(t['shades']) if ratio(hex_rgb(s), W) >= 4.5), 'none')
    fixed[name] = h45
    P(name, hx, '%.2f' % r0, '%d%%' % k45, h45, '%.2f' % ratio(hex_rgb(h45), W), tp, '%d%%' % k3, h3, '%d%% %s %.2f' % (km, hm, ratio(hex_rgb(hm), W)))
json.dump(fixed, open(os.path.join(work, 'fixed.json'), 'w'))

# ---- Test C: encode and phone-size scaling
FW, FH, RH, ROWS = 1080, 1920, 160, 12
def ppm_of(hx, path, w=FW, h=FH):
    c = bytes(hex_rgb(hx)); open(path, 'wb').write(b'P6 %d %d 255\n' % (w, h) + c * (w * h)); return path
def frame(bg, size, tag, rows):
    ft = '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf'
    f = ','.join("drawtext=fontfile=%s:text='Weekly tips':fontsize=%d:fontcolor=0x%s:x=60:y=%d+(%d-text_h)/2" % (ft, size, hx.lstrip('#'), i * RH, RH) for i, hx in enumerate(rows))
    png = os.path.join(work, tag + '.png')
    ppm = ppm_of(bg, os.path.join(work, tag + '.bg.ppm')); sh('ffmpeg -y -v error -i %s -vf "format=rgb24,%s" -frames:v 1 %s' % (ppm, f, png)); return png
def to_raw(src, w, h, vf, out, inopts=''):
    sh('ffmpeg -y -v error %s -i %s -vf "%s" -frames:v 1 -f rawvideo -pix_fmt rgb24 %s' % (inopts, src, vf, out)); return out
def encode(png, crf, mp4):
    sh('ffmpeg -y -v error -loop 1 -i %s -t 1 -r 30 -vf "scale=out_color_matrix=bt709:out_range=tv,format=yuv420p" -c:v libx264 -preset medium -crf %d -colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv %s' % (png, crf, mp4))
DEC = 'scale=in_color_matrix=bt709:in_range=tv:out_range=full,format=rgb24'
SW, SH = 390, 693
def stages(png, crf, tag):
    mp4 = os.path.join(work, tag + '.mp4'); encode(png, crf, mp4)
    s0 = to_raw(png, FW, FH, 'format=rgb24', os.path.join(work, tag + '.s0.rgb'))
    s1 = to_raw(mp4, FW, FH, 'select=eq(n\\,10),' + DEC, os.path.join(work, tag + '.s1.rgb'))
    s2 = to_raw(png, SW, SH, 'scale=%d:%d:flags=bicubic,format=rgb24' % (SW, SH), os.path.join(work, tag + '.s2.rgb'))
    s3 = to_raw(mp4, SW, SH, 'select=eq(n\\,10),' + DEC + ',scale=%d:%d:flags=bicubic,format=rgb24' % (SW, SH), os.path.join(work, tag + '.s3.rgb'))
    return [(s0, FW, FH), (s1, FW, FH), (s2, SW, SH), (s3, SW, SH)]
P('\nTEST C CONTROLS (encode crf 30, then phone-size scaling)')
# control 1: black left half, white right half; control 2: one flat colour
sh('ffmpeg -y -v error -i %s -vf "format=rgb24,drawbox=x=540:y=0:w=540:h=1920:color=white:t=fill" -frames:v 1 %s' % (ppm_of('#000000', os.path.join(work, 'ctl1.ppm')), os.path.join(work, 'ctl1.png')))
sh('ffmpeg -y -v error -i %s -frames:v 1 %s' % (ppm_of('#2563EB', os.path.join(work, 'ctl2.ppm')), os.path.join(work, 'ctl2.png')))
for tag in ('ctl1', 'ctl2'):
    sts = stages(os.path.join(work, tag + '.png'), 30, tag)
    res = []
    for (f, w, h), nm in zip(sts, ['source', 'encoded', 'source-scaled', 'encoded-scaled']):
        d = read_rgb(f, w, h)
        def px(x, y): o = (y * w + x) * 3; return tuple(d[o:o + 3])
        if tag == 'ctl1': r = ratio(px(int(w * .25), h // 2), px(int(w * .75), h // 2))
        else: r = ratio(px(int(w * .25), h // 2), px(int(w * .75), h // 2))
        res.append('%s %.2f (%s | %s)' % (nm, r, rgb_hex(px(int(w * .25), h // 2)), rgb_hex(px(int(w * .75), h // 2))))
    P(tag, ' ; '.join(res), '(expect ctl1 about 21, ctl2 exactly 1.00)')

def runC(bg, bgname, rows, size, label, crf=30):
    tag = 'c_%s_%d_%d' % (bgname, size, crf)
    bghex = {'white': '#FFFFFF', 'black': '#000000'}[bgname]
    png = frame(bghex, size, tag, rows)
    sts = stages(png, crf, tag)          # source, encoded, source-scaled, encoded-scaled
    src = read_rgb(sts[0][0], FW, FH)
    # stroke-interior mask for the whole frame, then its coverage at phone size (area scaling)
    full = bytearray()
    for i in range(ROWS): full += core_mask(src, FW, i * RH, (i + 1) * RH, hex_rgb(bghex), hex_rgb(rows[i]))
    gp = os.path.join(work, tag + '.core.gray'); open(gp, 'wb').write(bytes(x * 255 for x in full))
    gs = os.path.join(work, tag + '.cores.gray')
    sh('ffmpeg -y -v error -f rawvideo -pix_fmt gray -s %dx%d -i %s -vf scale=%d:%d:flags=area -f rawvideo -pix_fmt gray %s' % (FW, FH, gp, SW, SH, gs))
    small = open(gs, 'rb').read()
    imgs = [read_rgb(f, w, h) for (f, w, h) in sts]
    out = []
    for i in range(ROWS):
        vals = []
        for k, (d, (f, w, h)) in enumerate(zip(imgs, sts)):
            if w == FW:
                pick = [(x, y) for y in range(i * RH, (i + 1) * RH) for x in range(1, FW - 1) if full[y * FW + x]]
            else:
                y0 = int(round(i * RH * h / FH)); y1 = int(round((i + 1) * RH * h / FH))
                pick = [(x, y) for y in range(y0 + 2, y1 - 2) for x in range(w) if small[y * w + x] >= 230]
            fg, n = mean_rgb(d, w, 0, pick)
            bgc, _ = mean_rgb(d, w, 0, [(x, y) for y in range(int(round(i * RH * h / FH)) + 2, int(round((i + 1) * RH * h / FH)) - 2) for x in range(0, 12)])
            vals.append((ratio(fg, bgc), n) if fg else (None, 0))
        out.append(vals)
    return out
results = {}
for bgname, size, crf in [('white', 96, 30), ('white', 36, 30), ('black', 96, 30), ('black', 36, 30), ('white', 36, 40), ('black', 36, 40)]:
    res = runC(bgname, bgname, [hx for _, hx in cols], size, '', crf)
    results[(bgname, size, crf)] = res
    P('\nTEST C: %s background, text %d px in a 1080x1920 frame, crf %d' % (bgname, size, crf))
    P('name\thex\tnominal\tsource\tencoded\tsource_scaled_390 (core px)\tencoded_scaled_390 (core px)')
    for (name, hx), vals in zip(cols, res):
        nom = ratio(hex_rgb(hx), {'white': W, 'black': B_}[bgname])
        P(name, hx, '%.2f' % nom, *[('%.2f (%d)' % v if v[0] else 'none (0)') if j >= 2 else ('%.2f' % v[0]) for j, v in enumerate(vals)])
    nomf = lambda hx: ratio(hex_rgb(hx), {'white': W, 'black': B_}[bgname])
    for j, nm in ((1, 'encode only'), (2, 'scaling only'), (3, 'encode then scaling')):
        dv = [v[j][0] / nomf(hx) - 1 for (n, hx), v in zip(cols, res)]
        P('%s: deviation from nominal, min %.1f%%, max %.1f%%' % (nm, 100 * min(dv), 100 * max(dv)))
json.dump({'%s_%d_%d' % k: v for k, v in results.items()}, open(os.path.join(work, 'resultsC.json'), 'w'))
open('test-results.txt', 'w').write('\n'.join(log) + '\n')
