"""Example receiver: verify, deduplicate and durably accept events.

Set FULLREACH_WEBHOOK_SECRET (from Fullreach) and FULLREACH_WORKSPACE_ID /
FULLREACH_PROJECT_ID. Run: uvicorn webhook_receiver:app --host 127.0.0.1 --port 8080
Expose /fullreach through your HTTPS reverse proxy on port 443.
A separate agent worker consumes the SQLite inbox. Receipt itself never sends
messages to Telegram or executes instructions from event content.
"""
import hashlib
import hmac
import json
import os
import sqlite3
import time
from contextlib import asynccontextmanager
from fastapi import FastAPI,HTTPException,Request


def database():
    return sqlite3.connect(os.getenv('FULLREACH_INBOX_DB','fullreach-inbox.sqlite3'),timeout=10)


@asynccontextmanager
async def lifespan(app):
    if len(os.getenv('FULLREACH_WEBHOOK_SECRET',''))<32:
        raise RuntimeError('Set FULLREACH_WEBHOOK_SECRET to the signing secret from Fullreach')
    for name in ('FULLREACH_WORKSPACE_ID','FULLREACH_PROJECT_ID'):
        if not os.getenv(name,'').isdigit():raise RuntimeError('Set '+name)
    with database() as db:
        db.execute('CREATE TABLE IF NOT EXISTS inbox(event_id TEXT PRIMARY KEY, body BLOB NOT NULL, received_at INTEGER NOT NULL, processed_at INTEGER)')
    yield


app=FastAPI(lifespan=lifespan)


@app.post('/fullreach',status_code=202)
async def receive(request:Request):
    body=bytearray()
    async for chunk in request.stream():
        body.extend(chunk)
        if len(body)>65536:raise HTTPException(413,'Event too large')
    timestamp=request.headers.get('x-fullreach-timestamp','')
    signature=request.headers.get('x-fullreach-signature','')
    if len(timestamp)>20 or not timestamp.isascii() or not timestamp.isdigit() or abs(int(time.time())-int(timestamp))>300:
        raise HTTPException(401,'Expired or invalid signature timestamp')
    expected='v1='+hmac.new(os.environ['FULLREACH_WEBHOOK_SECRET'].encode(),timestamp.encode()+b'.'+body,hashlib.sha256).hexdigest()
    if not signature.isascii() or not hmac.compare_digest(expected,signature):raise HTTPException(401,'Invalid signature')
    try:data=json.loads(body)
    except (ValueError,UnicodeError):raise HTTPException(422,'Invalid event') from None
    if not isinstance(data,dict) or not isinstance(data.get('id'),str) or len(data['id'])>100 or data['id']!=request.headers.get('x-fullreach-event-id'):
        raise HTTPException(422,'Invalid event identity')
    if data.get('workspace_id')!=int(os.environ['FULLREACH_WORKSPACE_ID']) or data.get('project_id')!=int(os.environ['FULLREACH_PROJECT_ID']):
        raise HTTPException(403,'Unexpected project or workspace')
    with database() as db:
        previous=db.execute('SELECT body FROM inbox WHERE event_id=?',(data['id'],)).fetchone()
        if previous and previous[0]!=bytes(body):raise HTTPException(409,'Event identity reused with different data')
        db.execute('INSERT OR IGNORE INTO inbox(event_id,body,received_at) VALUES(?,?,?)',(data['id'],bytes(body),int(time.time())))
    return {'accepted':True}
