import click


@click.group()
def main() -> None:
    """Matyan CLI."""


@main.command()
@click.option("--host", default="0.0.0.0", help="Server host")
@click.option("--port", default=53800, help="Server port")
def start(host: str, port: int) -> None:
    """Start the Matyan server."""
    import uvicorn  # noqa: PLC0415

    uvicorn.run("matyan_backend.app:app", host=host, port=port, workers=1)


@main.command(name="ingest-worker")
def ingest_worker() -> None:
    """Run the data-ingestion Kafka consumer worker."""
    import asyncio  # noqa: PLC0415

    from matyan_backend.workers.ingestion import IngestionWorker  # noqa: PLC0415

    asyncio.run(IngestionWorker().start())


@main.command(name="control-worker")
def control_worker() -> None:
    """Run the control-events Kafka consumer worker."""
    import asyncio  # noqa: PLC0415

    from matyan_backend.workers.control import ControlWorker  # noqa: PLC0415

    asyncio.run(ControlWorker().start())


@main.command()
def reindex() -> None:
    """Rebuild all Tier 1 secondary indexes from run metadata."""
    from matyan_backend.storage.fdb_client import ensure_directories, init_fdb  # noqa: PLC0415
    from matyan_backend.storage.indexes import rebuild_indexes  # noqa: PLC0415

    db = init_fdb()
    ensure_directories(db)
    count = rebuild_indexes(db)
    click.echo(f"Indexed {count} run(s).")


@main.command(name="finish-stale")
@click.option("--timeout-hours", default=24, type=float, help="Finish runs active longer than this many hours")
def finish_stale(timeout_hours: float) -> None:
    """Mark runs as finished if they have been active longer than a timeout."""
    import time  # noqa: PLC0415

    from matyan_backend.storage.fdb_client import ensure_directories, init_fdb  # noqa: PLC0415
    from matyan_backend.storage.indexes import lookup_by_active  # noqa: PLC0415
    from matyan_backend.storage.runs import get_run_meta, update_run_meta  # noqa: PLC0415

    db = init_fdb()
    ensure_directories(db)

    cutoff = time.time() - timeout_hours * 3600
    active_hashes = lookup_by_active(db, True)
    finished = 0
    for run_hash in active_hashes:
        meta = get_run_meta(db, run_hash)
        created_at = meta.get("created_at", 0)
        if created_at < cutoff:
            update_run_meta(db, run_hash, active=False, finalized_at=time.time())
            finished += 1
            click.echo(f"  Finished stale run: {run_hash} (created {time.time() - created_at:.0f}s ago)")

    click.echo(f"Finished {finished} stale run(s) out of {len(active_hashes)} active.")


if __name__ == "__main__":
    main()
