from typing import Literal

import click

from tgzr.cli.utils import TGZRCliGroup

from ..session import Session
from ..studio import Studio
from ..project import Project

from .utils import pass_session


@click.group(
    cls=TGZRCliGroup,
    help="Manage Projects in the Studio",
)
def project():
    pass


@project.command(
    "run",
    context_settings=dict(
        ignore_unknown_options=True,
    ),
)
@click.argument(
    "cmd_name",
)
@click.argument("cmd_args", nargs=-1, type=click.UNPROCESSED)
@pass_session
def project_run(session: Session, cmd_name: str, cmd_args: list[str]):
    """
    Run a Project cmd.
    """
    studio: Studio | None = session.get_selected_studio()
    if studio is None:
        raise click.UsageError("Please select a studio first.")
    project: Project | None = session.get_selected_project()
    if project is None:
        raise click.UsageError("Please select a project first.")
    studio.run_cmd(cmd_name, cmd_args, project.name)


@project.command
@click.option(
    "-s",
    "--shell",
    default="auto",
    help='The shell to use, one of ["xonsh", "cmd", "powershell", "auto"] (defaults to "auto").',
)
@pass_session
def shell(
    session: Session,
    shell: Literal["xonsh", "cmd", "powershell", "auto"] = "auto",
):
    """
    Open a shell configured for the studio.
    """
    studio: Studio | None = session.get_selected_studio()
    if studio is None:
        raise click.UsageError("Please select a studio or set a default one.")
    project: Project | None = session.get_selected_project()
    if project is None:
        raise click.UsageError("Please select a project first.")
    if not project.exists():
        raise click.UsageError(f"Project {project.name} does not exist.")
    studio.shell(shell_type=shell, project_name=project.name)
