"""
Local manifest handling for g-gremlin.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Optional

from googleapiclient.errors import HttpError

from g_gremlin import google_client
from g_gremlin.models import SheetState

STATE_DIR = Path(".g_gremlin")
STATE_FILE = STATE_DIR / "state.json"


def load_state() -> Optional[SheetState]:
    """
    Load the stored SheetState from the local manifest, if it exists.
    """
    if not STATE_FILE.exists():
        return None

    try:
        data = json.loads(STATE_FILE.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return None

    return SheetState.from_dict(data)


def save_state(state: SheetState) -> None:
    """
    Persist the SheetState to the local manifest.
    """
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    STATE_FILE.write_text(json.dumps(state.to_dict(), indent=2), encoding="utf-8")


def check_remote_not_changed(state: SheetState) -> bool:
    """
    Compare stored ETag/revision with the current remote metadata.

    Returns True if unchanged; False if changed or if metadata cannot be read.
    """
    try:
        metadata = google_client.get_sheet_metadata(state.spreadsheet_id)
    except HttpError:
        return False

    stored_marker = state.concurrency_token
    remote_marker = metadata.get("headRevisionId") or metadata.get("modifiedTime")

    if not stored_marker or not remote_marker:
        return False

    return stored_marker == remote_marker
