"""Typer command surface for the local check-in store."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Annotated

import typer

from checkin_cli.store import EventStore, RecordRequest


app = typer.Typer(add_completion=False, no_args_is_help=True)


@app.callback()
def main(
    ctx: typer.Context,
    home: Annotated[Path, typer.Option(file_okay=False, dir_okay=True, writable=True)],
) -> None:
    """Select the profile-local data home for every command."""
    ctx.obj = EventStore.for_standalone(home)


@app.command()
def record(
    ctx: typer.Context,
    message_id: Annotated[str, typer.Option(min=1)],
    received_at: Annotated[str, typer.Option(min=1)],
    text: Annotated[str, typer.Option(min=1)],
    supersedes: Annotated[str | None, typer.Option()] = None,
) -> None:
    """Append one Telegram-like check-in and rebuild derived views."""
    store = ctx.obj
    result = store.record(RecordRequest(message_id, received_at, text, supersedes))
    typer.echo(
        json.dumps(
            {"outcome": result.outcome, "event_id": result.event_id, "safety_flags": result.safety_flags},
            ensure_ascii=False,
        )
    )


@app.command("import-history")
def import_history(
    ctx: typer.Context,
    source: Annotated[Path, typer.Option(exists=True, dir_okay=False, readable=True)],
    range_label: Annotated[str, typer.Option(min=1)],
) -> None:
    """Import only immutable source hashes and stable heading provenance."""
    store = ctx.obj
    imported = store.import_history(source, range_label)
    typer.echo(json.dumps({"outcome": "imported", "event_count": imported}, ensure_ascii=False))


@app.command("import-baseline")
def import_baseline(
    ctx: typer.Context,
    manifest: Annotated[Path, typer.Option(exists=True, dir_okay=False, readable=True)],
) -> None:
    """Import dated, partial historical measurements from the approved manifest."""
    store = ctx.obj
    imported = store.import_baseline(manifest)
    typer.echo(json.dumps({"outcome": "baseline_imported", "event_count": imported}, ensure_ascii=False))


if __name__ == "__main__":
    app()
