"""Feedback + re-run queue store for the asset library spike (prod). One JSON file, guarded by an flock.
Used by server.py (the page) and cli.py (the re-run worker on the local box, through ssh)."""
import fcntl, json, os, time, uuid
from contextlib import contextmanager
DATA = os.environ.get('FAL_DATA', '/home/forge/fal-feedback/data')
PATH = os.path.join(DATA, 'state.json')


@contextmanager
def locked():
    os.makedirs(DATA, exist_ok=True)
    with open(os.path.join(DATA, '.lock'), 'w') as lk:
        fcntl.flock(lk, fcntl.LOCK_EX)
        try:
            st = json.load(open(PATH))
        except (OSError, ValueError):
            st = {'assets': {}, 'jobs': []}
        yield st
        tmp = PATH + '.tmp'
        json.dump(st, open(tmp, 'w'), indent=1)
        os.replace(tmp, PATH)


def now():
    return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())


def add_feedback(st, aid, text, user):
    a = st['assets'].setdefault(aid, {'feedback': []})
    item = {'t': now(), 'text': text[:4000], 'user': user}
    a['feedback'].append(item)
    return item


def lane(j):
    """Astra re-runs (20-40 min) and quick jobs (lighter copy, use-in-games switch) queue separately."""
    return 'rerun' if j.get('kind', 'rerun') == 'rerun' else 'quick'


def add_job(st, aid, text, user, kind='rerun', params=None):
    for j in st['jobs']:
        if j['asset'] == aid and j['state'] in ('queued', 'running') and lane(j) == lane({'kind': kind}):
            return None, j
    j = {'id': uuid.uuid4().hex[:12], 'asset': aid, 'kind': kind, 'params': params or {}, 'feedback': text[:4000], 'user': user,
         'state': 'queued', 'queued': now(), 'started': None, 'finished': None, 'note': '', 'version': None}
    st['jobs'].append(j)
    return j, None
