from pathlib import Path
import json
import os
import subprocess

import typer

from l4d2host.instances import delete_instance, initialize_instance, reset_instance, start_instance, stop_instance
from l4d2host.logs import stream_instance_logs
from l4d2host.status import get_instance_status
from l4d2host.steam_install import SteamInstaller


app = typer.Typer(no_args_is_help=True)


def _exit_from_subprocess_error(exc: subprocess.CalledProcessError) -> None:
    if exc.stderr:
        typer.echo(exc.stderr, err=True)
    raise typer.Exit(code=exc.returncode)


@app.command()
def install() -> None:
    # LEFT4ME_STEAMCMD lets deployment pin an absolute path (e.g. when the
    # binary lives outside PATH or its steamcmd.sh resolves $0 via dirname,
    # which breaks under PATH-symlink invocation). Default keeps PATH lookup
    # for dev/tests.
    steamcmd = os.environ.get("LEFT4ME_STEAMCMD", "steamcmd")
    try:
        SteamInstaller(steamcmd=steamcmd).install_or_update(passthrough=True)
    except subprocess.CalledProcessError as exc:
        _exit_from_subprocess_error(exc)


@app.command()
def initialize(name: str, spec: Path = typer.Option(..., "-f")) -> None:
    try:
        initialize_instance(name, spec, passthrough=True)
    except subprocess.CalledProcessError as exc:
        _exit_from_subprocess_error(exc)


@app.command()
def start(name: str) -> None:
    try:
        start_instance(name, passthrough=True)
    except subprocess.CalledProcessError as exc:
        _exit_from_subprocess_error(exc)


@app.command()
def stop(name: str) -> None:
    try:
        stop_instance(name, passthrough=True)
    except subprocess.CalledProcessError as exc:
        _exit_from_subprocess_error(exc)


@app.command()
def delete(name: str) -> None:
    try:
        delete_instance(name, passthrough=True)
    except subprocess.CalledProcessError as exc:
        _exit_from_subprocess_error(exc)


@app.command()
def reset(name: str) -> None:
    try:
        reset_instance(name, passthrough=True)
    except subprocess.CalledProcessError as exc:
        _exit_from_subprocess_error(exc)


@app.command()
def status(name: str, json_output: bool = typer.Option(False, "--json")) -> None:
    instance_status = get_instance_status(name)
    if json_output:
        typer.echo(
            json.dumps(
                {
                    "state": instance_status.state,
                    "raw_active_state": instance_status.raw_active_state,
                    "raw_sub_state": instance_status.raw_sub_state,
                }
            )
        )
        return
    typer.echo(instance_status.state)


@app.command()
def logs(
    name: str,
    lines: int = typer.Option(200, "--lines"),
    follow: bool = typer.Option(True, "--follow/--no-follow"),
) -> None:
    try:
        for line in stream_instance_logs(name, lines=lines, follow=follow):
            typer.echo(line)
    except subprocess.CalledProcessError as exc:
        _exit_from_subprocess_error(exc)
