from __future__ import annotations

import json
import sys

import click

from .core.manager import HistoryManager
from .storage import SQLiteStorage


@click.group()
@click.option(
    "--db",
    type=click.Path(path_type=str),
    required=True,
    help="Path to SQLite database",
)
@click.pass_context
def cli(ctx: click.Context, db: str) -> None:
    """Manage unmake sessions."""
    ctx.obj = HistoryManager(SQLiteStorage(db))


@cli.command("list-sessions")
@click.option("--limit", default=10, show_default=True, help="Number of sessions to show")
@click.pass_obj
def list_sessions(manager: HistoryManager, limit: int) -> None:
    sessions = manager.list_sessions(limit=limit)

    if not sessions:
        click.echo("No sessions found.")
        return

    click.echo(f"{'ID':<40} {'Status':<15} {'Created':<25} {'Context'}")
    click.echo("-" * 140)
    for session in sessions:
        created = session.created_at.strftime("%Y-%m-%d %H:%M:%S")
        context = str(session.context)[:60]
        click.echo(f"{session.session_id:<40} {session.status.value:<15} {created:<25} {context}")


@cli.command("show-session")
@click.argument("session_id")
@click.pass_obj
def show_session(manager: HistoryManager, session_id: str) -> None:
    session = manager.get_session(session_id)
    if not session:
        click.echo(f"Session not found: {session_id}", err=True)
        raise SystemExit(1)

    click.echo(f"Session ID: {session.session_id}")
    click.echo(f"Status: {session.status.value}")
    click.echo(f"Created: {session.created_at}")
    click.echo(f"Completed: {session.completed_at}")
    click.echo(f"Context: {session.context}")
    click.echo(f"Undo Count: {session.undo_count}")

    operations = manager.get_operations(session_id)
    click.echo(f"\nOperations ({len(operations)}):")
    for op in operations:
        click.echo(f"  [{op.sequence}] {op.op_type}: {json.dumps(op.payload, sort_keys=True)}")


@cli.command("undo")
@click.argument("session_id")
@click.option("--force", is_flag=True, help="Force undo without confirmation")
@click.pass_obj
def undo(manager: HistoryManager, session_id: str, force: bool) -> None:
    del manager
    del force
    click.echo("Undo functionality requires operation registry.")
    click.echo("This will be implemented in a future version.")
    raise SystemExit(1)


def main() -> None:
    cli.main(args=sys.argv[1:], prog_name="unmake", standalone_mode=True)


if __name__ == "__main__":
    main()
