"""Lighter copies: the active-version rule (what games get) and the two job lanes. usage: python3 test/test_lighter.py"""
import json, os, subprocess, sys, tempfile
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, 'lib')); sys.path.insert(0, os.path.join(ROOT, 'feedback'))
import card as cardlib  # noqa: E402

ok = 0


def check(name, cond):
    global ok
    assert cond, name
    ok += 1


v = lambda n, st, **k: {'version': n, 'status': st, **k}
check('newest non-draft wins', cardlib.active([v(1, 'approved'), v(2, 'approved')])['version'] == 2)
check('a draft lighter copy never reaches games', cardlib.active([v(1, 'approved'), v(2, 'draft')])['version'] == 1)
check('an explicit active marker wins over newer versions', cardlib.active([v(1, 'approved', active=True), v(2, 'approved'), v(3, 'draft')])['version'] == 1)
check('a withdrawn version never becomes active', cardlib.active([v(1, 'approved'), v(2, 'deprecated'), v(3, 'draft')])['version'] == 1)
check('all drafts: newest', cardlib.active([v(1, 'draft'), v(2, 'draft')])['version'] == 2)
check('active is not a runtime field (no new release)', 'active' not in cardlib.RUNTIME and 'lighter' not in cardlib.RUNTIME)

with tempfile.TemporaryDirectory() as d:
    os.environ['FAL_DATA'] = d
    import store
    with store.locked() as st:
        j1, _ = store.add_job(st, 'prop.x.y/a', 'fix it', 'op')
        j2, busy = store.add_job(st, 'prop.x.y/a', '', 'op', 'lighter', {'target': 5000})
        check('a lighter job is not blocked by a running re-run', j2 is not None and busy is None)
        _, busy = store.add_job(st, 'prop.x.y/a', '', 'op', 'activate', {'version': 2})
        check('one open quick job per asset', busy is not None and busy['id'] == j2['id'])
        st['jobs'].append({'id': 'old', 'asset': 'prop.x.y/b', 'state': 'queued'})  # a job from before lanes existed
    cli = os.path.join(ROOT, 'feedback', 'cli.py')
    run = lambda *a: json.loads(subprocess.run([sys.executable, cli, *a], capture_output=True, text=True, cwd=os.path.join(ROOT, 'feedback'),
                                               env={**os.environ, 'FAL_DATA': d}).stdout or '{}')
    check('next (no lane) = the Astra re-run', run('next')['id'] == j1['id'])
    check('next quick = the lighter job', run('next', 'quick')['id'] == j2['id'])
    check('quick lane busy: nothing more', run('next', 'quick') == {})
    check('a job without kind is a re-run, queued behind the running one', run('next') == {})
print(f'{ok} checks passed')
