"""Version + Release-Notes-Endpoints fuer das Frontend-Update-System."""
import json
import subprocess
from datetime import datetime, timezone
from pathlib import Path
from fastapi import APIRouter

REPO_ROOT = Path(__file__).resolve().parent.parent.parent
RELEASES_FILE = REPO_ROOT / 'RELEASES.json'

# Version-Hash beim Boot einmalig auslesen.
try:
    COMMIT_HASH = subprocess.check_output(
        ['git', 'rev-parse', '--short=10', 'HEAD'],
        cwd=str(REPO_ROOT), text=True, timeout=5
    ).strip()
except Exception:
    COMMIT_HASH = 'unknown'

DEPLOYED_AT = datetime.now(timezone.utc).isoformat()

router = APIRouter(tags=['version'])


@router.get('/api/version')
def version():
    return {'commit': COMMIT_HASH, 'deployed_at': DEPLOYED_AT}


@router.get('/api/release-notes')
def release_notes(since: str = '', limit: int = 5):
    """Liefert Release-Notes seit der gegebenen Version.

    'since' = letzte vom User gesehene Version. Liefert alle Eintraege NEUER
    als diese Version. Ohne 'since' werden die letzten 'limit' Eintraege
    geliefert.
    """
    if not RELEASES_FILE.exists():
        return {'entries': [], 'current': COMMIT_HASH}
    try:
        with open(RELEASES_FILE, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except Exception as e:
        return {'entries': [], 'error': f'parse-failed: {e}'}

    if since:
        result = []
        for entry in data:
            if entry.get('version') == since:
                break
            result.append(entry)
        return {'entries': result[:limit], 'current': COMMIT_HASH}

    return {'entries': data[:limit], 'current': COMMIT_HASH}
