"""SoccerRating review queue, independent from the authoritative match database.

No website secrets are stored by this module. Background scraping is disabled
until an authenticated connector is separately configured and verified.
"""
from __future__ import annotations
import base64, hashlib, json, os, re, sqlite3, threading, uuid, time
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from contextlib import closing

HERE = Path(__file__).resolve().parent
QUEUE_DB = HERE / 'soccerrating_queue.db'
LOCK = threading.RLock()
STRATEGIES = {f'{2 + i*.05:.2f}': i + 1 for i in range(7)}
MAX_BATCH = 250
# Authenticated source-only trace metadata. No automatic fixture/category inference.
SOURCE_COMPETITION_CODE_RE = re.compile(r'[A-Z]{2,6}[0-9]{1,3}')

class QueueConnection(sqlite3.Connection):
    def __exit__(self, exc_type, exc, tb):
        try: return super().__exit__(exc_type,exc,tb)
        finally: self.close()

def db():
    conn = sqlite3.connect(QUEUE_DB, timeout=20, factory=QueueConnection)
    conn.row_factory = sqlite3.Row
    conn.execute('PRAGMA busy_timeout=20000')
    return conn

def setup():
    with LOCK:
        c = db()
        try:
            c.executescript('''
              CREATE TABLE IF NOT EXISTS candidates (
                id TEXT PRIMARY KEY, identity_hash TEXT NOT NULL UNIQUE,
                strategy TEXT NOT NULL, sheet INTEGER NOT NULL,
                match_date TEXT NOT NULL, home TEXT NOT NULL, away TEXT NOT NULL,
                home_odds REAL NOT NULL, draw_odds REAL NOT NULL, away_odds REAL NOT NULL,
                league TEXT NOT NULL DEFAULT '', country TEXT NOT NULL DEFAULT '',
                status TEXT NOT NULL DEFAULT 'pending',
                imported_match_id TEXT NOT NULL DEFAULT '',
                created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
              );
              CREATE INDEX IF NOT EXISTS idx_sr_status ON candidates(status,match_date);
              CREATE TABLE IF NOT EXISTS scans (
                id TEXT PRIMARY KEY, scanned_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
                new_count INTEGER NOT NULL, by_strategy TEXT NOT NULL, source TEXT NOT NULL
              );
              CREATE TABLE IF NOT EXISTS alerts (
                id TEXT PRIMARY KEY, scan_id TEXT, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
                headline TEXT NOT NULL, detail TEXT NOT NULL, push_status TEXT NOT NULL DEFAULT 'pending',
                UNIQUE(scan_id)
              );
              CREATE TABLE IF NOT EXISTS subscriptions (
                endpoint_hash TEXT PRIMARY KEY, payload TEXT NOT NULL,
                created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
              );
              CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
              CREATE TABLE IF NOT EXISTS archive_redetection_hashes (
                identity_hash TEXT PRIMARY KEY,
                removed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
              );
            ''')
            # Idempotent metadata migration: do not rewrite existing queue rows.
            candidate_columns = {r['name'] for r in c.execute('PRAGMA table_info(candidates)')}
            if 'source_competition_code' not in candidate_columns:
                # SQLite-consistent snapshot BEFORE changing an older queue.
                backup_dir=HERE/'Backups'
                backup_dir.mkdir(parents=True,exist_ok=True)
                backup=backup_dir/(
                    'Before_Source_Competition_Code_'+
                    datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')+'.db')
                with closing(sqlite3.connect(backup)) as saved:
                    c.backup(saved)
                c.execute("ALTER TABLE candidates ADD COLUMN source_competition_code TEXT NOT NULL DEFAULT ''")
            # Add diagnostics without changing or discarding previous scan records.
            columns = {r['name'] for r in c.execute('PRAGMA table_info(scans)')}
            if 'outcomes_json' not in columns:
                c.execute("ALTER TABLE scans ADD COLUMN outcomes_json TEXT NOT NULL DEFAULT '{}'")
            c.commit()
        finally: c.close()

def norm(s):
    return re.sub(r'\s+', ' ', str(s or '').strip()).casefold()

def date_for_pick(value, today=None):
    s = str(value or '').strip()
    today = today or date.today()
    try:
        if re.fullmatch(r'\d{4}-\d{2}-\d{2}', s):
            v = date.fromisoformat(s)
        elif re.fullmatch(r'\d{1,2}[/.]\d{1,2}[/.]\d{2,4}', s):
            d, m, y = map(int, re.split(r'[/.]', s))
            if y < 100: y += 2000
            v = date(y, m, d)
        elif re.fullmatch(r'\d{1,2}[/.]\d{1,2}', s):
            d, m = map(int, re.split(r'[/.]', s))
            candidates = [date(y,m,d) for y in (today.year-1,today.year,today.year+1) if not (m==2 and d==29 and y%4)]
            near = [x for x in candidates if 0 <= (x-today).days <= 3]
            if len(near) != 1: raise ValueError('Ambiguous match date; supply a full year.')
            v = near[0]
        else: raise ValueError('Invalid match date; use YYYY-MM-DD or DD/MM/YYYY.')
    except (ValueError, OverflowError) as exc:
        raise ValueError('Match date is invalid or ambiguous. Use YYYY-MM-DD.') from exc
    # SoccerRating picks typically appear within 48h. Do not invent future 2027 matches.
    if not 0 <= (v-today).days <= 4:
        raise ValueError('This is not an upcoming Betting Pick (date outside the five-day collection window).')
    return v.isoformat()

def candidate(data, strategy, today=None, *, source=''):
    strategy = str(strategy).strip()
    if strategy in {'2','2.0'}: strategy='2.00'
    if strategy not in STRATEGIES: raise ValueError('Unknown strategy. Expected 2.00–2.30 in 0.05 steps.')
    if not isinstance(data,dict): raise ValueError('Invalid match row.')
    dt = date_for_pick(data.get('date'),today)
    home,away = str(data.get('home') or '').strip(),str(data.get('away') or '').strip()
    if not home or not away or home.casefold()==away.casefold() or max(len(home),len(away))>120:
        raise ValueError('Valid distinct home/away teams are required (120 characters maximum).')
    odds=[]
    for key in ['homeOdds','drawOdds','awayOdds']:
        try: n=float(data.get(key))
        except (TypeError,ValueError): raise ValueError('Missing or invalid '+key)
        if not 1<n<=1000 or n!=n or n in (float('inf'),float('-inf')): raise ValueError('Invalid '+key)
        odds.append(n)
    if abs(odds[0] - float(strategy)) > .001: raise ValueError('Home odds do not match the selected SoccerRating strategy '+strategy)
    identity = '|'.join([str(STRATEGIES[strategy]),dt,norm(home),norm(away)])
    fid = hashlib.sha256(identity.encode()).hexdigest()
    # Only the authenticated site connector may assert original competition
    # code labels; user-submitted/manual source captures cannot forge them.
    code=str(data.get('sourceCompetitionCode') or '').strip()
    if (source not in ('authenticated-browser','authenticated-browser-partial')
            or not SOURCE_COMPETITION_CODE_RE.fullmatch(code)):
        code=''
    return {'id': 'sr_'+fid[:24], 'identity_hash':fid, 'strategy':strategy,'sheet':STRATEGIES[strategy],
            'match_date':dt,'home':home,'away':away,'home_odds':odds[0],'draw_odds':odds[1],'away_odds':odds[2],
            'source_competition_code':code}

def collect(rows_by_strategy, *, source='authorized-browser', today=None,
            existing_match_exists=None, scan_outcomes=None):
    """Persist a complete scan report and notify ONLY on truly new matches.

    scan_outcomes is the connector's per-strategy result, using states
    'ok', 'empty', or 'error'. Missing/unverified states fail closed.
    """
    if not isinstance(rows_by_strategy, dict):
        raise ValueError('Expected strategy-to-matches mapping.')
    if any(k not in STRATEGIES for k in rows_by_strategy):
        raise ValueError('Unknown source strategy.')
    if sum(len(v) for v in rows_by_strategy.values() if isinstance(v,list)) > MAX_BATCH:
        raise ValueError('Too many matches in one scan.')
    parsed=[]
    for strategy, rows in rows_by_strategy.items():
        if not isinstance(rows, list):
            raise ValueError('Each strategy needs a list of matches.')
        for match in rows:
            parsed.append(candidate(match, strategy, today=today, source=source))
    if scan_outcomes is not None and not isinstance(scan_outcomes,dict):
        raise ValueError('Scan details must be a mapping.')
    counts={}
    known={}
    restored={}
    newly_discovered=[]
    archive_redetected=[]
    with LOCK:
        c=db()
        try:
            c.execute('BEGIN IMMEDIATE')
            for record in parsed:
                count_before=counts.get(record['strategy'],0)
                already_registered = bool(existing_match_exists and existing_match_exists(record))
                if already_registered:
                    record = {**record,'status':'already-registered'}
                keys=list(record)
                cur=c.execute('INSERT OR IGNORE INTO candidates ('+','.join(keys)+') VALUES ('+','.join('?' for _ in keys)+')',[record[k] for k in keys])
                # Fill only an empty source code on an unchanged pending
                # identity. Never overwrite a conflicting code or change
                # league/country, approvals, status, odds or alerts.
                if not cur.rowcount and record['source_competition_code']:
                    c.execute('''UPDATE candidates SET source_competition_code=?
                          WHERE identity_hash=? AND source_competition_code=''
                          AND status='pending' ''',
                        (record['source_competition_code'],record['identity_hash']))
                if cur.rowcount and not already_registered:
                    previously_deleted = c.execute(
                        'SELECT 1 FROM archive_redetection_hashes WHERE identity_hash=?',
                        (record['identity_hash'],)
                    ).fetchone()
                    if previously_deleted:
                        restored[record['strategy']] = (
                            restored.get(record['strategy'], 0) + 1
                        )
                        archive_redetected.append(record)
                    else:
                        counts[record['strategy']] = (
                            counts.get(record['strategy'], 0) + 1
                        )
                elif (not cur.rowcount and not already_registered
                      and existing_match_exists is not None):
                    # A previously approved UTC kickoff can cross the original
                    # SoccerRating date. Before reopening an imported match,
                    # check its exact saved master Match ID, not source date.
                    prior = c.execute(
                        'SELECT status,imported_match_id FROM candidates WHERE identity_hash=?',
                        (record['identity_hash'],)).fetchone()
                    if prior and prior['status']=='imported':
                        if not prior['imported_match_id']:
                            raise ValueError('Imported queue entry has no master Match ID; manual investigation required.')
                        linked = {**record,'imported_match_id':prior['imported_match_id']}
                        if existing_match_exists(linked):
                            known[record['strategy']] = known.get(record['strategy'],0)+1
                            continue
                    # Reopen a still-upcoming pick only when the linked master
                    # record is truly absent. Preserve deleted/tombstoned ID
                    # provenance, existing manual decisions and source identity.
                    # Never reopen a dismissed fixture or create a new alert.
                    recovered = c.execute("""UPDATE candidates
                        SET status='pending', home=?, away=?, home_odds=?,
                            draw_odds=?, away_odds=?, updated_at=CURRENT_TIMESTAMP
                        WHERE identity_hash=? AND status IN ('already-registered','imported')""",
                        (record['home'], record['away'], record['home_odds'],
                         record['draw_odds'], record['away_odds'],
                         record['identity_hash']))
                    if recovered.rowcount:
                        restored[record['strategy']] = restored.get(record['strategy'],0)+1
                    else:
                        known[record['strategy']] = known.get(record['strategy'],0)+1
                else:
                    known[record['strategy']] = known.get(record['strategy'],0)+1
                if counts.get(record['strategy'],0)>count_before:
                    newly_discovered.append(record)
            outcomes={}
            if scan_outcomes is not None:
                for strategy in STRATEGIES:
                    raw=scan_outcomes.get(strategy, {})
                    state=raw.get('state') if isinstance(raw,dict) else None
                    examined=sum(1 for r in parsed if r['strategy']==strategy)
                    new=counts.get(strategy,0)
                    old=known.get(strategy,0)
                    reopened=restored.get(strategy,0)
                    if state == 'error' or state not in ('ok','empty'):
                        label='Failed'
                    elif state == 'empty' and examined == 0:
                        label='Empty'
                    elif state == 'ok' and examined and (new or reopened):
                        label='Collected'
                    elif state == 'ok' and examined:
                        label='Already known'
                    else:
                        label='Failed'  # Inconsistent connector report.
                    detail={'status':label,'found':examined if label!='Failed' else 0,
                            'new':new,'restored':reopened,'alreadyKnown':old}
                    if label=='Failed':
                        detail['error']=str(raw.get('error') if isinstance(raw,dict) else 'No verified scan result.')[:180]
                    outcomes[strategy]=detail
            new_count=sum(counts.values())
            scan_id=uuid.uuid4().hex
            c.execute('INSERT INTO scans(id,new_count,by_strategy,source,outcomes_json) VALUES(?,?,?,?,?)',
                      (scan_id,new_count,json.dumps(counts),source,json.dumps(outcomes)))
            alert_id=None
            if new_count or archive_redetected:
                alert_id=uuid.uuid4().hex
                if new_count and archive_redetected:
                    headline=(f'{new_count} new and {len(archive_redetected)} '
                              'rediscovered SoccerRating matches')
                elif archive_redetected:
                    n=len(archive_redetected)
                    headline=f'{n} rediscovered SoccerRating match'+('es' if n!=1 else '')
                else:
                    headline=f'{new_count} new SoccerRating match'+('es' if new_count!=1 else '')
                archive_hashes={r['identity_hash'] for r in archive_redetected}
                detail='\n'.join(
                    f"{'Rediscovered from archive: ' if item['identity_hash'] in archive_hashes else ''}{item['match_date']} | "
                    f"{item['home']} vs {item['away']} | "
                    f"Strategy {item['strategy']} "
                    f"(Sheet {item['sheet']}) | "
                    f"Home {item['home_odds']:.2f}, "
                    f"Draw {item['draw_odds']:.2f}, "
                    f"Away {item['away_odds']:.2f}"
                    for item in sorted(
                        newly_discovered + archive_redetected,
                        key=lambda r:(
                            r['match_date'],
                            r['sheet'],
                            r['home']
                        )
                    )
                )
                c.execute('INSERT INTO alerts(id,scan_id,headline,detail) VALUES(?,?,?,?)',
                          (alert_id,scan_id,headline,detail))
            c.commit()
            return {'newCount':new_count,'byStrategy':counts,'knownByStrategy':known,
                    'restoredByStrategy':restored,'restoredCount':sum(restored.values()),
                    'examined':len(parsed),'scanId':scan_id,'alertId':alert_id,
                    'notified':False,'outcomes':outcomes,
                    'notificationFixtures':sorted(newly_discovered + archive_redetected,
                       key=lambda r:(r['match_date'],r['sheet'],r['home']))}
        except Exception:
            c.rollback();raise
        finally:c.close()

def queue():
    with db() as c:
        return [dict(r) for r in c.execute('SELECT * FROM candidates WHERE status=? ORDER BY match_date,sheet,home',('pending',))]

def archived_matches():
    with db() as c:
        return [dict(r) for r in c.execute(
            "SELECT * FROM candidates WHERE status='dismissed' "
            "ORDER BY updated_at DESC, match_date, sheet"
        )]


def restore_archived(identifier, *, existing_match_exists=None):
    with LOCK:
        with db() as c:
            row = c.execute(
                "SELECT * FROM candidates "
                "WHERE id=? AND status='dismissed'",
                (identifier,)
            ).fetchone()

            if row is None:
                raise ValueError(
                    'This match is no longer in the archive.'
                )

            if (existing_match_exists is not None
                    and existing_match_exists(dict(row))):
                raise ValueError(
                    'This fixture already exists in the Match Registry.'
                )

            changed_row=c.execute(
                "UPDATE candidates SET status='pending', "
                "updated_at=CURRENT_TIMESTAMP "
                "WHERE id=? AND status='dismissed'",
                (identifier,)
            )
            if changed_row.rowcount != 1:
                raise ValueError('Archive restore did not update this match.')

            fixture=dict(row)
            alert_id=uuid.uuid4().hex
            detail=(
                f"Restored from archive: {fixture['match_date']} | "
                f"{fixture['home']} vs {fixture['away']} | "
                f"Strategy {fixture['strategy']} (Sheet {fixture['sheet']}) | "
                f"Home {fixture['home_odds']:.2f}, "
                f"Draw {fixture['draw_odds']:.2f}, Away {fixture['away_odds']:.2f}"
            )
            c.execute(
                'INSERT INTO alerts(id,headline,detail) VALUES(?,?,?)',
                (alert_id,'1 restored SoccerRating match',detail)
            )

    return {'status':'pending','restored':True,
            'alertId':alert_id,'notificationFixtures':[fixture]}


def permanently_delete_archived(identifier):
    with LOCK:
        with db() as c:
            row = c.execute(
                "SELECT identity_hash FROM candidates "
                "WHERE id=? AND status='dismissed'",
                (identifier,)
            ).fetchone()

            if row is None:
                raise ValueError(
                    'This match is no longer in the archive.'
                )

            c.execute(
                "INSERT OR IGNORE INTO "
                "archive_redetection_hashes(identity_hash) VALUES (?)",
                (row['identity_hash'],)
            )

            c.execute(
                "DELETE FROM candidates "
                "WHERE id=? AND status='dismissed'",
                (identifier,)
            )

    return {
        'deleted':True,
        'rediscoveryAllowed':True
    }


def alerts(limit=50):
    with db() as c:
        rows=[dict(r) for r in c.execute('SELECT id,created_at,headline,detail,push_status FROM alerts ORDER BY created_at DESC,id DESC LIMIT ?', (min(max(int(limit),1),100),))]
    diagnostic=_push_diagnostics_read()
    for row in rows:
        if row['id'] in diagnostic:
            info=diagnostic[row['id']]
            row['pushDiagnostics']={
                'accepted':info.get('accepted',0),
                'rejected':info.get('rejected',0),
                'retryPending':info.get('retryPending',0),
                'transportErrors':info.get('transportErrors',0),
                'httpRejected':info.get('httpRejected',0),
                'devices':info.get('devices',[]),
                'recordedAt':info.get('recordedAt','')
            }
    return rows

def stats():
    with db() as c:
        row=c.execute("SELECT COUNT(*) total FROM candidates WHERE status='pending'").fetchone()
        last=c.execute('SELECT scanned_at,new_count,source,outcomes_json FROM scans ORDER BY rowid DESC LIMIT 1').fetchone()
        recent=dict(last) if last else None
        if recent:
            recent['outcomes']=json.loads(recent.pop('outcomes_json') or '{}')
        return {'pending':row['total'],'lastScan':recent}

def get_row(identifier):
    with db() as c:
        row=c.execute('SELECT * FROM candidates WHERE id=?',(identifier,)).fetchone()
        return dict(row) if row else None

def update_row(identifier, *, action, league='', country='', kickoff_time='', verified_date='', existing_match_exists=None, save_match=None, match_id_reserved=None, saved_match_lookup=None):
    """No master writes until explicit review/approval. Callback injected by desktop."""
    if action not in ('dismiss','approve'): raise ValueError('Unsupported review action.')
    with LOCK:
        row=get_row(identifier)
        if not row or row['status']!='pending': raise ValueError('Match is no longer pending.')
        if action=='dismiss':
            with db() as c: c.execute("UPDATE candidates SET status='dismissed',updated_at=CURRENT_TIMESTAMP WHERE id=? AND status='pending'",(identifier,))
            return {'status':'dismissed'}
        league = str(league or '').strip()
        country = str(country or '').strip()
        if len(league)>120: raise ValueError('League cannot exceed 120 characters.')
        if len(country)>120: raise ValueError('Country name is too long.')
        if not isinstance(kickoff_time,str): raise ValueError('Kickoff Time must be HH:MM.')
        kickoff_time=kickoff_time.strip()
        if kickoff_time and not re.fullmatch(r'(?:[01]\d|2[0-3]):[0-5]\d', kickoff_time):
            raise ValueError('Kickoff Time must use 24-hour HH:MM (00:00–23:59).')
        verified_date = str(verified_date or row['match_date']).strip()
        try:
            date.fromisoformat(verified_date)
        except ValueError as exc:
            raise ValueError('Verified kickoff date must use YYYY-MM-DD.') from exc
        # The candidate retains its original source identity and late-review eligibility.
        # FA_SR_SPLIT_COMMIT_RECOVERY_V1: A crash may occur AFTER the master
        # SQLite commit but BEFORE the queue's imported-status commit. The
        # first import's Match ID is deterministic from the source identity.
        # Recover an exactly matching earlier save without saving a duplicate.
        # Conflicting earlier saves fail closed even if the reviewer changes
        # the date, country, league, kickoff or odds on a subsequent attempt.
        if not row['imported_match_id']:
            first_id = 'S'+str(row['sheet'])+'-SR'+row['identity_hash'][:20].upper()
            if saved_match_lookup is None:
                raise ValueError('Master Match ID recovery check unavailable; no import performed.')
            saved = saved_match_lookup(first_id)
            if saved is not None:
                expected = {'id':first_id, 'sheet':row['sheet'], 'date':verified_date,
                            'home':row['home'], 'away':row['away'],
                            'homeOdds':row['home_odds'], 'drawOdds':row['draw_odds'],
                            'awayOdds':row['away_odds'], 'league':league,
                            'country':country, 'kickoffTime':kickoff_time}
                same = (all(norm(saved.get(key))==norm(value) for key,value in expected.items()
                            if key not in ('homeOdds','drawOdds','awayOdds'))
                        and all(abs(float(saved.get(key))-float(expected[key]))<0.000001
                                for key in ('homeOdds','drawOdds','awayOdds')))
                if not same:
                    raise ValueError('A previous Match ID save already exists with different approved fields. Inspect the Match Registry; no duplicate import performed.')
                with db() as c:
                    changed=c.execute("""UPDATE candidates
                        SET status='imported',league=?,country=?,imported_match_id=?,
                            updated_at=CURRENT_TIMESTAMP
                        WHERE id=? AND status='pending' AND imported_match_id=''""",
                        (league,country,first_id,identifier))
                    if changed.rowcount!=1:
                        raise ValueError('Review queue changed during interrupted-save recovery; reload before retrying.')
                return {'status':'imported','matchId':first_id,
                        'recoveredAfterInterruptedSave':True}
        # Duplicate protection also uses the verified date being imported.
        import_row = dict(row)
        import_row['match_date'] = verified_date
        if existing_match_exists(import_row):
            raise ValueError('Match already exists in the master registry on the verified date.')
        # The master database permanently reserves deleted Match IDs.
        # On reapproval after an earlier importer approval, use a fresh
        # unique ID instead of attempting to reuse the tombstoned one.
        match_id = ('S'+str(row['sheet'])+'-SR'+
                    (uuid.uuid4().hex[:20].upper() if row['imported_match_id']
                     else row['identity_hash'][:20].upper()))
        # FA_IMPORTER_TOMBSTONE_REIMPORT_V1
        # Keep the tombstone. Generate a different unique ID only when needed.
        if match_id_reserved is None:
            raise ValueError('Master Match ID reservation check is unavailable.')
        if match_id_reserved(match_id):
            for _ in range(20):
                replacement = 'S'+str(row['sheet'])+'-SR'+uuid.uuid4().hex[:20].upper()
                if not match_id_reserved(replacement):
                    match_id = replacement
                    break
            else:
                raise ValueError('Could not reserve a new Match ID. No import performed.')
        item={'id':match_id,
              'sheet':row['sheet'],'date':verified_date, 'home':row['home'],'away':row['away'],
              'homeOdds':row['home_odds'],'drawOdds':row['draw_odds'],'awayOdds':row['away_odds'],
              'score':'','halfTimeScore':'','league':league,'country':country,
              'kickoffTime':kickoff_time}
        result=save_match(item)
        # save_match may have committed in SQLite but workbook sync may still be pending.
        with db() as c:
            changed=c.execute("UPDATE candidates SET status='imported',league=?,country=?,imported_match_id=?,updated_at=CURRENT_TIMESTAMP WHERE id=? AND status='pending'",
                              (league,country,item['id'],identifier))
            if changed.rowcount!=1:
                # Master may already be committed; the next identical review
                # can reconcile safely using its deterministic Match ID.
                raise ValueError('Master saved but review queue changed; reload before retrying.')
        return {'status':'imported','matchId':item['id'],**result}

def add_subscription(subscription):
    if not isinstance(subscription,dict) or not isinstance(subscription.get('endpoint'),str): raise ValueError('Invalid push subscription.')
    endpoint=subscription['endpoint']
    if not endpoint.startswith('https://') or len(endpoint)>2000 or not all(subscription.get('keys',{}).get(x) for x in ('p256dh','auth')):
        raise ValueError('Incomplete push subscription.')
    key=hashlib.sha256(endpoint.encode()).hexdigest()
    with LOCK,db() as c:
        c.execute('INSERT OR REPLACE INTO subscriptions(endpoint_hash,payload) VALUES(?,?)',(key,json.dumps(subscription)))
    return {'subscribed':True}

def drop_subscription(endpoint):
    key=hashlib.sha256(str(endpoint).encode()).hexdigest()
    with LOCK,db() as c:c.execute('DELETE FROM subscriptions WHERE endpoint_hash=?',(key,))
    return {'subscribed':False}

def get_setting(key):
    with db() as c:
        row=c.execute('SELECT value FROM settings WHERE key=?',(key,)).fetchone()
        return row['value'] if row else ''

def set_setting(key,value):
    if key not in ('collector_enabled','vapid_contact'): raise ValueError('Invalid setting.')
    with LOCK,db() as c:
        c.execute('INSERT OR REPLACE INTO settings(key,value) VALUES (?,?)',(key,str(value)))

def configure_push(email):
    email=str(email or '').strip()
    if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[^\s@]+',email) or len(email)>160:
        raise ValueError('Enter a valid contact email for the Web Push service.')
    ensure_push_key()
    set_setting('vapid_contact',email)
    return push_config()

def create_test_alert():
    aid=uuid.uuid4().hex
    with LOCK,db() as c:
        c.execute("INSERT INTO alerts(id,headline,detail) VALUES(?,?,?)",
                  (aid,'Test notification','Phone notification setup test · no matches were imported'))
    return aid

def push_config():
    # Never silently generate and use a fake contact address for a real push service.
    address = (os.environ.get('FA_VAPID_CONTACT_EMAIL') or get_setting('vapid_contact')).strip()
    keypath = HERE/'private_soccerrating_vapid.pem'
    if not address or '@' not in address or not keypath.exists():
        return {'available':False,'publicKey':'','message':'Configure a Web Push contact email and install optional notification dependencies.'}
    try:
        from cryptography.hazmat.primitives import serialization
        public=serialization.load_pem_private_key(keypath.read_bytes(),password=None).public_key().public_bytes(
            serialization.Encoding.X962,serialization.PublicFormat.UncompressedPoint)
        return {'available':True,'publicKey':base64.urlsafe_b64encode(public).decode().rstrip('='),'message':''}
    except Exception as exc:
        return {'available':False,'publicKey':'','message':str(exc)}

def _notification_body(detail):
    lines = [
        line.strip()
        for line in str(detail or '').splitlines()
        if line.strip()
    ]

    if not lines:
        return 'New SoccerRating picks await review.'

    message = '\n'.join(lines[:3])

    if len(lines)>3:
        message += (
            f'\n+{len(lines)-3} more matches. '
            'Open the Review Queue.'
        )

    return message[:700]


# FA_SR_PUSH_PER_DEVICE_DIAGNOSTICS_V1: hashed endpoint IDs only, no secret material.
PUSH_DIAGNOSTICS_PATH = HERE / 'soccerrating_push_delivery.json'
PUSH_SEND_LOCK = threading.Lock()
PUSH_MAX_ATTEMPTS = 4
PUSH_TTL = 3600
PUSH_BACKOFF = (30,120,300)
_PUSH_RETRY_STATES = {'pending','retry_pending','inflight'}


def _push_diagnostics_read():
    try:
        raw = json.loads(PUSH_DIAGNOSTICS_PATH.read_text(encoding='utf-8'))
        return raw if isinstance(raw, dict) else {}
    except (FileNotFoundError, ValueError, OSError):
        return {}

def _push_diagnostics_save(alert_id, results, *, payload=None, expires_at=None):
    """Durable per-device checkpoint. No endpoints, keys or raw exception text."""
    with LOCK:
        history = _push_diagnostics_read()
        if PUSH_DIAGNOSTICS_PATH.exists():
            # Do not discard delivery history on corrupt/unreadable JSON.
            verified=json.loads(PUSH_DIAGNOSTICS_PATH.read_text(encoding='utf-8'))
            if not isinstance(verified,dict):raise RuntimeError('Invalid push delivery history')
            history=verified
        old=history.get(str(alert_id),{})
        entry={
            'accepted':sum(r['state']=='accepted' for r in results),
            'rejected':sum(r['state']!='accepted' for r in results),
            'retryPending':sum(r['state'] in _PUSH_RETRY_STATES for r in results),
            'transportErrors':sum(r.get('failureKind')=='transport' for r in results),
            'httpRejected':sum(r.get('failureKind')=='http' for r in results),
            'devices':results,
            'recordedAt':datetime.now(timezone.utc).isoformat(timespec='seconds'),
            'version':2,
            'expiresAt':expires_at if expires_at is not None else old.get('expiresAt',0),
            'payload':payload if payload is not None else old.get('payload',{})
        }
        history[str(alert_id)]=entry
        # Keep all still-active retry records. Bound completed history as before.
        if len(history)>150:
            active={k:v for k,v in history.items() if isinstance(v,dict) and
                    v.get('expiresAt',0)>time.time() and v.get('retryPending',0)}
            recent=dict(sorted(history.items(),key=lambda x:x[1].get('recordedAt',''))[-150:])
            history={**recent,**active}
        tmp=PUSH_DIAGNOSTICS_PATH.with_suffix('.tmp')
        with tmp.open('w',encoding='utf-8') as stream:
            json.dump(history,stream,separators=(',',':'))
            stream.flush();os.fsync(stream.fileno())
        os.replace(tmp,PUSH_DIAGNOSTICS_PATH)
        return entry

# FA_SR_PUSH_APPROVED_V2: no queue writes, no fabricated fixture matching.
def fixture_status(identifier):
    """Return saved state for one exact queue ID. Never approve or modify it."""
    if not re.fullmatch(r'sr_[a-f0-9]{24}', str(identifier or '')):
        raise ValueError('Invalid SoccerRating fixture ID.')
    with db() as conn:
        row=conn.execute(
            'SELECT id,status,home,away,match_date,strategy,sheet,imported_match_id '
            'FROM candidates WHERE id=?', (identifier,)
        ).fetchone()
    if not row:
        return {'found':False,'status':'not-found'}
    d=dict(row)
    return {'found':True,'status':d['status'],'fixture':d}

def _push_exact_fixture(alert, provided=None):
    """Single-fixture alerts only. Batch alerts never target an arbitrary first match."""
    lines=[line.strip() for line in str(alert.get('detail') or '').splitlines() if line.strip()]
    if len(lines)!=1:
        return None
    if isinstance(provided,list) and len(provided)==1:
        item=provided[0]
        if isinstance(item,dict) and re.fullmatch(r'sr_[a-f0-9]{24}',str(item.get('id') or '')):
            return item
    # Safe retry path: match the archived original alert line to a UNIQUE stored
    # queue identity. Do not guess by team names alone or alter a queue record.
    line=lines[0]
    for prefix in ('Restored from archive: ', 'Rediscovered from archive: '):
        if line.startswith(prefix):
            line=line[len(prefix):]
            break
    matches=[]
    with db() as conn:
        records=conn.execute(
            'SELECT id,status,home,away,match_date,strategy,sheet,'
            'home_odds,draw_odds,away_odds FROM candidates'
        ).fetchall()
    for row in records:
        r=dict(row)
        signature=(f"{r['match_date']} | {r['home']} vs {r['away']} | "
                   f"Strategy {r['strategy']} (Sheet {r['sheet']}) | ")
        if line.startswith(signature):
            matches.append(r)
            if len(matches)>1:
                return None
    return matches[0] if len(matches)==1 else None

def build_push_payload(alert, *, image_url=None, notification_fixtures=None):
    """Build readable compact text + optional image + exact-identity routing."""
    item=_push_exact_fixture(alert,notification_fixtures)
    tag='fa-sr-'+str(alert['id'])[:20]
    if item:
        title='SoccerRating | Match Alert'
        odds=(f"Home {float(item['home_odds']):.2f} · "
              f"Draw {float(item['draw_odds']):.2f} · "
              f"Away {float(item['away_odds']):.2f}")
        body=(f"{item['home']} vs {item['away']}\n"
              f"{odds} · Strategy {item['strategy']}")
        out={'title':title,'body':body[:240],'tag':tag,
             'fixtureId':str(item['id']),
             'url':'/soccerrating-importer?fixture='+str(item['id'])}
    else:
        title=str(alert['headline'] or 'SoccerRating Review Queue')[:78]
        count=len([l for l in str(alert.get('detail') or '').splitlines() if l.strip()])
        body=(f"{count} fixtures await individual review. Open the Review Queue."
              if count>1 else 'Open the SoccerRating Review Queue for details.')
        if title=='Test notification':
            body='Notification test only. No fixture was imported or approved.'
        out={'title':title,'body':body,'tag':tag,'url':'/soccerrating-importer'}
    if (image_url and
        re.fullmatch(r'/soccerrating-push-images/[a-f0-9]{32}\.png',image_url)):
        out['image']=image_url
    return out


def _push_created_epoch(value):
    try:
        t=datetime.fromisoformat(str(value).replace('Z','+00:00'))
        return t.replace(tzinfo=timezone.utc).timestamp() if t.tzinfo is None else t.timestamp()
    except (ValueError,TypeError,OverflowError):
        return 0

def _push_failure(exc, response=None):
    """Classify without logging endpoint URLs, keys, response body or credentials."""
    from requests.exceptions import ConnectionError, Timeout, SSLError
    response=response if response is not None else getattr(exc,'response',None)
    code=getattr(response,'status_code',None)
    if isinstance(code,int):
        retry=code in (408,425,429) or 500<=code<=599
        after=0
        try:after=max(0,min(PUSH_TTL,int(response.headers.get('Retry-After','0'))))
        except (ValueError,TypeError,AttributeError):pass
        return 'http','HTTP '+str(code),code,retry,after
    kind=type(exc).__name__
    if isinstance(exc,SSLError):kind='SSLError'
    elif isinstance(exc,Timeout):kind='Timeout'
    elif isinstance(exc,ConnectionError):kind='ConnectionError'
    # Bounded retry only for known connection/timeout errors or a WebPushException
    # without a response; invalid keys/payloads and programming errors are terminal.
    retry=isinstance(exc,(ConnectionError,Timeout,OSError)) or kind=='WebPushException'
    return 'transport' if retry else 'local',kind,None,retry,0

def _push_device_state(device, previous):
    if previous is None:return {'device':device,'state':'pending','attempts':0,'nextRetry':0}
    row=dict(previous)
    if 'attempts' not in row:
        row['attempts']=1
        code=row.get('http')
        if row.get('state')!='accepted':
            row['failureKind']='transport' if code is None else 'http'
            row['error']='Legacy transport failure' if code is None else 'HTTP '+str(code)
            row['state']='retry_pending' if code is None or code in (408,425,429) or isinstance(code,int) and 500<=code<=599 else 'rejected'
        row['nextRetry']=0
    return row

def send_alerts(*, only_id=None, image_url=None, notification_fixtures=None):
    """Per-device retry; never resend an acknowledged success or expired alert."""
    if not PUSH_SEND_LOCK.acquire(blocking=bool(only_id)):
        return {'sent':0,'status':'busy'}
    try:
        return _send_alerts_locked(only_id=only_id,image_url=image_url,notification_fixtures=notification_fixtures)
    finally:
        PUSH_SEND_LOCK.release()

def _send_alerts_locked(*, only_id=None, image_url=None, notification_fixtures=None):
    config=push_config()
    if not config['available']:return {'sent':0,'status':'not-configured'}
    try:from pywebpush import webpush, WebPushException
    except ImportError:return {'sent':0,'status':'pywebpush-not-installed'}
    now=time.time()
    # Existing legacy "sent" records can include partial delivery. Only recent
    # ones with an explicit recorded failure are recovered; never replay history.
    with db() as c:
        subs=[json.loads(r['payload']) for r in c.execute('SELECT payload FROM subscriptions')]
        all_alerts=[dict(r) for r in c.execute(
            "SELECT id,headline,detail,created_at,push_status FROM alerts WHERE "+
            ("id=?" if only_id else "created_at>=?")+" ORDER BY created_at LIMIT 150",
            ([only_id] if only_id else [datetime.fromtimestamp(now-PUSH_TTL-600,timezone.utc).strftime('%Y-%m-%d %H:%M:%S')]))]
    by_device={}
    for sub in subs:
        ep=sub.get('endpoint','')
        if not ep:continue
        device=hashlib.sha256(ep.encode('utf-8')).hexdigest()[:10]
        if device in by_device:raise RuntimeError('Ambiguous push device fingerprint')
        by_device[device]=sub
    history=_push_diagnostics_read()
    if PUSH_DIAGNOSTICS_PATH.exists():
        history=json.loads(PUSH_DIAGNOSTICS_PATH.read_text(encoding='utf-8'))
        if not isinstance(history,dict):raise RuntimeError('Invalid push delivery history')
    sent=0;attempted=0
    for alert in all_alerts:
        aid=alert['id'];created=_push_created_epoch(alert['created_at']);deadline=created+PUSH_TTL
        old=history.get(aid)
        if not created or created>now+60:continue
        if old is None and alert['push_status']=='sent':continue
        if not only_id and old is None and now-created<60:continue
        if not old and now>=deadline:continue
        if old:
            # Freeze the original target list; no old alerts to newly registered devices.
            raw=old.get('devices')
            if not isinstance(raw,list) or not raw:continue
            devices=[_push_device_state(str(x['device']),x) for x in raw]
            if len({x['device'] for x in devices})!=len(devices):raise RuntimeError('Ambiguous delivery history')
        else:
            devices=[_push_device_state(x,None) for x in by_device]
        if not devices:continue
        payload=(old or {}).get('payload')
        if not isinstance(payload,dict) or not payload:
            chosen=image_url if only_id==aid else None
            if not chosen and (HERE/'soccerrating_push_images'/(aid+'.png')).is_file():
                chosen='/soccerrating-push-images/'+aid+'.png'
            payload=build_push_payload(alert,image_url=chosen,
                notification_fixtures=notification_fixtures if only_id==aid else None)
        changed=False
        for row in devices:
            if row['state'] not in _PUSH_RETRY_STATES:continue
            device=row['device'];now=time.time()
            if device not in by_device:
                row.update(state='inactive',nextRetry=0);changed=True;continue
            if now>=deadline or int(row.get('attempts',0))>=PUSH_MAX_ATTEMPTS:
                row.update(state='exhausted',nextRetry=0);changed=True;continue
            if float(row.get('nextRetry',0))>now:continue
            sub=by_device[device];attempt=row.get('attempts',0)+1
            # Checkpoint before any network call. A crash/unknown acknowledgement
            # can be retried with the same notification tag after a bounded delay.
            row.update(state='inflight',attempts=attempt,nextRetry=now+PUSH_BACKOFF[min(attempt-1,2)])
            _push_diagnostics_save(aid,devices,payload=payload,expires_at=deadline)
            attempted+=1
            response=None;exc=None
            try:
                response=webpush(subscription_info=sub,data=json.dumps(payload,ensure_ascii=False),
                    vapid_private_key=str(HERE/'private_soccerrating_vapid.pem'),
                    vapid_claims={'sub':'mailto:'+(os.environ.get('FA_VAPID_CONTACT_EMAIL') or get_setting('vapid_contact'))},
                    ttl=max(1,min(PUSH_TTL,int(deadline-time.time()))),timeout=12)
                code=getattr(response,'status_code',None)
                if isinstance(code,int) and 200<=code<300:
                    row.update(state='accepted',http=code,nextRetry=0,error='',failureKind='')
                else:exc=RuntimeError('Unexpected push response')
            except Exception as error:exc=error
            if exc is not None:
                kind,label,code,retry,after=_push_failure(exc,response)
                row.update(http=code,error=label,failureKind=kind,nextRetry=0)
                if code in (404,410):
                    row['state']='expired'
                    drop_subscription(sub['endpoint']);by_device.pop(device,None)
                elif retry and attempt<PUSH_MAX_ATTEMPTS and time.time()<deadline:
                    due=time.time()+max(PUSH_BACKOFF[min(attempt-1,2)],after)
                    if due<deadline:row.update(state='retry_pending',nextRetry=due)
                    else:row['state']='exhausted'
                else:row['state']='exhausted' if retry else 'rejected'
                print('SoccerRating push:',device,kind,label,'attempt',attempt,'state',row['state'],flush=True)
            _push_diagnostics_save(aid,devices,payload=payload,expires_at=deadline)
            changed=True
        accepted=sum(r['state']=='accepted' for r in devices)
        # Preserve legacy complete records; reconcile any persisted checkpoint if
        # process died before the alert summary update.
        status='sent' if accepted==len(devices) else 'partial' if accepted else 'failed'
        if changed or (old and status!=alert['push_status']):
            _push_diagnostics_save(aid,devices,payload=payload,expires_at=deadline)
            with LOCK,db() as c:c.execute('UPDATE alerts SET push_status=? WHERE id=?',(status,aid))
        if changed and accepted:sent+=1
    return {'sent':sent,'attempted':attempted,'status':'ok' if attempted else 'nothing-due'}


def ensure_push_key():
    try:
        from cryptography.hazmat.primitives.asymmetric import ec
        from cryptography.hazmat.primitives import serialization
    except ImportError: raise RuntimeError('Install cryptography to generate Web Push credentials.')
    keypath=HERE/'private_soccerrating_vapid.pem'
    if keypath.exists(): return
    key=ec.generate_private_key(ec.SECP256R1())
    raw=key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.TraditionalOpenSSL,serialization.NoEncryption())
    with open(keypath,'xb') as f: f.write(raw)
    try: os.chmod(keypath,0o600)
    except OSError: pass
