"""
CLI entry point for the ToRivers SDK.

This module provides the main CLI command group and registers
all subcommands for the `torivers` CLI tool.
"""

from __future__ import annotations

import sys

import click
from rich.console import Console

from torivers_sdk import __version__

console = Console()


@click.group()
@click.version_option(version=__version__, prog_name="torivers-sdk")
@click.pass_context
def cli(ctx: click.Context) -> None:
    """
    ToRivers SDK - Build automations for the ToRivers marketplace.

    Use these commands to create, test, validate, and submit automations.

    \b
    Quick start:
      torivers init my-automation    Create a new automation project
      cd my-automation
      torivers run                   Run the automation locally
      torivers test                  Run tests
      torivers validate              Check for submission readiness
      torivers submit                Submit for review
    """
    ctx.ensure_object(dict)


@cli.command()
@click.argument("name")
@click.option(
    "--template",
    "-t",
    type=click.Choice(["basic", "data-pipeline", "ai-analysis", "webhook-handler"]),
    default="basic",
    help="Template to use for the new automation",
)
@click.option(
    "--author",
    "-a",
    "author_name",
    type=str,
    default="",
    help="Author name for the automation",
)
@click.option(
    "--email",
    "-e",
    "author_email",
    type=str,
    default="",
    help="Author email for the automation",
)
@click.option(
    "--description",
    "-d",
    type=str,
    default="",
    help="Short description for the automation",
)
@click.option(
    "--list-templates",
    is_flag=True,
    help="List available templates",
)
def init(
    name: str,
    template: str,
    author_name: str,
    author_email: str,
    description: str,
    list_templates: bool,
) -> None:
    """
    Initialize a new automation project.

    Creates a new directory with automation boilerplate code.

    \b
    Examples:
      torivers init my-automation
      torivers init my-automation --template data-pipeline
      torivers init my-automation --author "John Doe" --email "john@example.com"
      torivers init --list-templates
    """
    from torivers_sdk.cli.commands.init import (
        init_project,
    )
    from torivers_sdk.cli.commands.init import list_templates as show_templates

    if list_templates:
        show_templates()
        return

    success = init_project(
        name=name,
        template=template,
        author_name=author_name,
        author_email=author_email,
        description=description,
    )
    if not success:
        sys.exit(1)


@cli.command()
@click.option(
    "--input",
    "-i",
    "input_file",
    type=click.Path(exists=True),
    help="JSON file with input data",
)
@click.option(
    "--input-json",
    "-j",
    "input_json",
    type=str,
    help="Input data as JSON string",
)
@click.option(
    "--mock-credentials",
    is_flag=True,
    default=True,
    help="Use mock credentials (default: True)",
)
def run(input_file: str | None, input_json: str | None, mock_credentials: bool) -> None:
    """
    Run the automation locally.

    Executes the automation in the local sandbox environment.

    \b
    Examples:
      torivers run
      torivers run --input sample_input.json
      torivers run --input-json '{"data": "test"}'
    """
    from torivers_sdk.cli.commands.run import run_automation

    success = run_automation(input_file, input_json, mock_credentials)
    if not success:
        sys.exit(1)


@cli.command()
@click.option(
    "--watch",
    "-w",
    is_flag=True,
    help="Watch for file changes and re-run tests",
)
@click.option(
    "--verbose",
    "-v",
    is_flag=True,
    help="Show verbose test output",
)
@click.option(
    "--coverage",
    is_flag=True,
    help="Generate coverage report",
)
@click.argument("path", required=False)
def test(watch: bool, verbose: bool, coverage: bool, path: str | None) -> None:
    """
    Run automation tests.

    Executes the test suite for the automation.

    \b
    Examples:
      torivers test
      torivers test --coverage
      torivers test --watch
      torivers test tests/test_specific.py
    """
    from torivers_sdk.cli.commands.test import run_tests

    success = run_tests(watch, verbose, coverage, path)
    if not success:
        sys.exit(1)


@cli.command()
@click.option(
    "--strict",
    "-s",
    is_flag=True,
    help="Enable strict validation mode",
)
@click.option(
    "--fix",
    is_flag=True,
    help="Attempt to auto-fix issues (not yet implemented)",
)
def validate(strict: bool, fix: bool) -> None:
    """
    Validate the automation for submission.

    Checks the automation for errors and best practices.

    \b
    Examples:
      torivers validate
      torivers validate --strict
    """
    from torivers_sdk.cli.commands.validate import validate_automation

    success = validate_automation(strict, fix)
    if not success:
        sys.exit(1)


@cli.command()
@click.option(
    "--message",
    "-m",
    help="Submission message",
)
@click.option(
    "--dry-run",
    is_flag=True,
    help="Validate without actually submitting",
)
def submit(message: str | None, dry_run: bool) -> None:
    """
    Submit the automation for review.

    Packages and uploads the automation to ToRivers for review.

    \b
    Examples:
      torivers submit
      torivers submit -m "Initial submission"
      torivers submit --dry-run
    """
    from torivers_sdk.cli.commands.submit import submit_automation

    success = submit_automation(message, dry_run)
    if not success:
        sys.exit(1)


@cli.command()
def login() -> None:
    """
    Authenticate with ToRivers.

    Opens a browser to authenticate your developer account.

    \b
    Example:
      torivers login
    """
    from torivers_sdk.cli.commands.auth import login as do_login

    success = do_login()
    if not success:
        sys.exit(1)


@cli.command()
def logout() -> None:
    """
    Log out from ToRivers.

    Removes stored authentication tokens.

    \b
    Example:
      torivers logout
    """
    from torivers_sdk.cli.commands.auth import logout as do_logout

    success = do_logout()
    if not success:
        sys.exit(1)


@cli.command()
def whoami() -> None:
    """
    Show current authentication status.

    Displays information about the currently logged in user.

    \b
    Example:
      torivers whoami
    """
    from torivers_sdk.cli.commands.auth import whoami as show_whoami

    show_whoami()


@cli.command()
@click.argument("submission_id", required=False)
def status(submission_id: str | None) -> None:
    """
    Check submission status.

    Shows the status of your submitted automations.

    \b
    Examples:
      torivers status
      torivers status SUB-20240101120000-abc123
    """
    from torivers_sdk.cli.commands.status import check_status

    success = check_status(submission_id)
    if not success:
        sys.exit(1)


@cli.command()
def templates() -> None:
    """
    List available project templates.

    Shows all templates that can be used with 'torivers init'.

    \b
    Example:
      torivers templates
    """
    from torivers_sdk.cli.commands.init import list_templates

    list_templates()


if __name__ == "__main__":
    cli()
