"""Anonymous, bounded release hints. Never imports credentials or executes feed data."""
import json as _notice_json
import os as _notice_os
import re as _notice_re
import tempfile as _notice_tempfile
import time as _notice_time
from pathlib import Path as _NoticePath
from urllib.request import Request as _NoticeRequest, build_opener as _notice_opener, HTTPRedirectHandler as _NoticeRedirect

NOTICE_REVISION = 3
NOTICE_URL = 'https://www.lyber.ai/lyber-connectors-release.json'
NOTICE_GUIDE = 'https://www.lyber.ai/docs/agents/connector-updates/'
NOTICE_TTL = 86400

class _NoticeNoRedirect(_NoticeRedirect):
    def redirect_request(self, *args, **kwargs):
        return None

def _notice_fetch_request():
    request = _NoticeRequest(NOTICE_URL, headers={'Accept': 'application/json', 'User-Agent': 'lyber-connector-updates/1'})
    with _notice_opener(_NoticeNoRedirect()).open(request, timeout=0.8) as response:
        raw = response.read(32769)
    if len(raw) > 32768:
        raise ValueError('Release feed too large')
    return _notice_json.loads(raw)

def _notice_fetch():
    # Socket timeouts alone do not bound a slow, trickling body. Keep startup bounded.
    import threading
    result = []
    def request():
        try: result.append(_notice_fetch_request())
        except Exception: pass
    worker = threading.Thread(target=request, daemon=True, name="lyber-release-fetch")
    worker.start()
    worker.join(timeout=1.0)
    if not result:
        raise TimeoutError('Release check unavailable')
    return result[0]

def connector_notice(channel, revision, version, cache, *, once=True, mark=True, fetch=None, now=None):
    """A daily fail-open check; the returned hint is for the human, never model context."""
    if _notice_os.environ.get('LYBER_UPDATE_NOTICES', '').lower() in {'0', 'false', 'off'}:
        return None
    try:
        now = _notice_time.time() if now is None else now
        path = _NoticePath(cache)
        if path.is_symlink():
            return None
        state = {}
        if path.is_file() and path.stat().st_size <= 32768:
            try:
                state = _notice_json.loads(path.read_text())
                if not isinstance(state, dict): state = {}
            except (ValueError, OSError): pass
        checked = state.get('checked_at')
        if not isinstance(checked, (int, float)) or isinstance(checked, bool) or not 0 <= now - checked < NOTICE_TTL:
            # Persist failed-check timing too: offline sessions must not hammer the feed.
            state['checked_at'] = now
            try:
                document = (fetch or _notice_fetch)()
                release = document.get('connectors', {}).get(channel) if document.get('schema_version') == 1 else None
                if (not isinstance(release, dict) or type(release.get('revision')) is not int
                        or not 1 <= release['revision'] <= 1000000000
                        or not isinstance(release.get('version'), str)
                        or not _notice_re.fullmatch(r'[0-9][A-Za-z0-9.+-]{0,40}', release['version'])):
                    raise ValueError('Invalid release metadata')
                state['release'] = {'revision': release['revision'], 'version': release['version']}
            except Exception:
                pass
        release = state.get('release', {})
        show = (isinstance(release, dict) and type(release.get('revision')) is int
                and revision < release['revision'] <= 1000000000
                and (not once or state.get('shown_revision') != release['revision'])
                and isinstance(release.get('version'), str)
                and _notice_re.fullmatch(r'[0-9][A-Za-z0-9.+-]{0,40}', release['version']))
        if show and once and mark:
            state['shown_revision'] = release['revision']
        path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
        if _notice_os.name != 'nt' and (path.parent.stat().st_uid != _notice_os.getuid() or path.parent.stat().st_mode & 0o022):
            return None
        fd, temporary = _notice_tempfile.mkstemp(prefix='.lyber-release-', dir=path.parent)
        try:
            with _notice_os.fdopen(fd, 'w') as stream:
                _notice_json.dump(state, stream)
            _notice_os.replace(temporary, path)
        finally:
            try: _notice_os.unlink(temporary)
            except FileNotFoundError: pass
        if show:
            return (f'Lyber connector update available: {version} → {release["version"]}. '
                    f'New models or connector improvements are available. Finish active work, then update and restart: {NOTICE_GUIDE}')
    except Exception:
        pass
    return None


if __name__ == '__main__':
    import argparse
    import sys
    parser = argparse.ArgumentParser(description='Check public Lyber connector releases; never installs or runs updates.')
    parser.add_argument('--connector', choices=['codex','hermes','opencode','claude'], default='claude')
    parser.add_argument('--hook', action='store_true', help='Display-only Claude SessionStart JSON; never injects model context')
    args = parser.parse_args()
    message = None
    # The Claude helper's own release revision; it moves only when this helper or its hook changes.
    CLAUDE_REVISION = 2
    # A Claude hook only applies when the user's current terminal selected Lyber.
    if not args.hook or _notice_os.environ.get('ANTHROPIC_BASE_URL','').rstrip('/') == 'https://api.lyber.ai':
        revision, version = {'codex': (NOTICE_REVISION, '1.2.0'), 'hermes': (3, '0.1.19'),
                             'opencode': (3, '0.5.0-rc.12'), 'claude': (CLAUDE_REVISION, '1.0.0')}[args.connector]
        message = connector_notice(args.connector, revision, version,
                                  _NoticePath.home()/'.cache/lyber'/('updates-'+args.connector+'.json'))
    if args.hook:
        print(_notice_json.dumps({'systemMessage': message} if message else {}))
    elif message:
        print(message)
    else:
        print('No new Lyber connector update notice. Offline checks never block your session.')
