"""Shared presentation theme only; intentionally independent of match/strategy SQLite."""
import json
import os
import tempfile
import threading
from datetime import datetime, timezone
from pathlib import Path

BASE = Path(__file__).resolve().parent
STATE = BASE / 'fa_shared_theme.json'
LOCK = threading.RLock()
THEMES = frozenset(('ocean', 'midnight', 'emerald', 'royal', 'graphite', 'coral', 'arctic', 'rose', 'terra', 'slate', 'crimson', 'aurora', 'porcelain-lilac', 'champagne-pearl', 'sage-meadow', 'mint-breeze', 'lavender-mist', 'peach-blossom', 'ivory-gold', 'pistachio-cream', 'sky-sorbet', 'blush-rose', 'lemon-chiffon', 'jade-mist', 'buttercup-ivory', 'orchid-bloom', 'seafoam-pearl', 'cinnamon-cream', 'apricot-glow', 'periwinkle-cloud', 'dusty-mauve', 'olive-linen', 'powder-blue', 'coral-pearl', 'pearl-turquoise', 'sand-dune', 'wisteria-light', 'berry-cream', 'mocha-latte', 'sunflower-milk', 'eucalyptus-fog', 'ocean-glass', 'frost-mint', 'ruby-pearl', 'honey-amber', 'twilight-lilac', 'fern-silk', 'cloud-iris', 'clay-blush', 'aqua-linen'))

class ThemeConflict(Exception):
    def __init__(self, current):
        super().__init__('Theme revision conflict')
        self.current = current

def _read_unlocked():
    if not STATE.exists():
        return {'theme':'ocean','revision':0,'updatedAt':None}
    data = json.loads(STATE.read_text(encoding='utf-8'))
    if (not isinstance(data, dict) or data.get('theme') not in THEMES or
        type(data.get('revision')) is not int or data['revision'] < 1):
        raise ValueError('Invalid shared theme preference file')
    return {k: data.get(k) for k in ('theme','revision','updatedAt')}

def read():
    with LOCK:
        return _read_unlocked()

def commit(payload):
    if not isinstance(payload,dict) or set(payload) != {'theme','expectedRevision'}:
        raise ValueError('Supply theme and expectedRevision only.')
    theme, expected = payload['theme'], payload['expectedRevision']
    if not isinstance(theme,str) or theme not in THEMES:
        raise ValueError('Unknown colour theme.')
    if type(expected) is not int or expected < 0:
        raise ValueError('Invalid revision.')
    with LOCK:
        current = _read_unlocked()
        if current['revision'] != expected:
            raise ThemeConflict(current)
        if current['theme'] == theme:
            return current
        next_state = {
            'theme': theme,
            'revision': current['revision'] + 1,
            'updatedAt': datetime.now(timezone.utc).isoformat(timespec='seconds')
        }
        fd, temp_path = tempfile.mkstemp(prefix='.fa_theme_',suffix='.tmp',dir=str(BASE))
        try:
            with os.fdopen(fd,'w',encoding='utf-8',newline='\n') as out:
                json.dump(next_state,out,ensure_ascii=False,separators=(',',':'))
                out.flush()
                os.fsync(out.fileno())
            os.replace(temp_path, STATE)
        finally:
            if os.path.exists(temp_path):
                os.unlink(temp_path)
        return next_state
