#
#   Imandra Inc.
#
#   codelogician/commands/cmd_server.py
#

from __future__ import annotations

from typing import Annotated

import typer

from codelogician.util import setup_logging

from .server.cmd_metamodel import app as metamodel_app
from .server.cmd_model import app as model_app
from .server.cmd_sketches import app as sketches_app
from .server.cmd_strategy import app as strategy_app

app = typer.Typer(name='server', no_args_is_help=True)


@app.callback()
def _root(
    ctx: typer.Context,
    base_url: str = typer.Option(
        'http://localhost:8000',
        '--base-url',
        envvar='CODELOGICIAN_SERVER_URL',
        help='Base URL for the CodeLogician server.',
    ),
    timeout: float = typer.Option(30.0, '--timeout', help='HTTP timeout in seconds.'),
    json_out: bool = typer.Option(
        True, '--json/--no-json', help='Pretty-print JSON output.'
    ),
):
    ctx.obj = {'base_url': base_url, 'timeout': timeout, 'json_out': json_out}


app.add_typer(metamodel_app, name='metamodel')
app.add_typer(model_app, name='model')
app.add_typer(sketches_app, name='sketches')
app.add_typer(strategy_app, name='strategy')


# fmt: off
@app.command(name='start', help='Start the server')
def run_server_cmd(
    dir   : Annotated[str, typer.Argument(help='Starting directory')],
    state : Annotated[str | None, typer.Option(help='Server state path')] = None,
    clean : Annotated[bool, typer.Option(help='Disregard existing strategy caches')] = False,
    config: Annotated[str, typer.Option(help='Configuration path')] = 'config/server_config.yaml',
    debug : Annotated[bool, typer.Option(help='Debug mode')] = False,
    addr  : Annotated[str, typer.Option(help='Server host/port')] = 'http://127.0.0.1:8000',
):
    from codelogician.server.main import run_server

    setup_logging(debug=debug)
    run_server(dir=dir, state=state, clean=clean, config=config, addr=addr)
# fmt: on


if __name__ == '__main__':
    app()
