"""CLI entry point for cascade."""

from __future__ import annotations

import argparse
import json
import sys
from collections.abc import Sequence

from cascade_fm._version import __version__
from cascade_fm.core.api import CascadeAPI
from cascade_fm.core.commit import CommitResult


def launch_gui() -> int:
    """Launch the cascade desktop application with PySide6.

    Returns:
        Exit code (0 for success, non-zero for failure).
    """
    try:
        from cascade_fm.gui.pyside6_app import launch
    except ImportError as e:
        print(f"Error: PySide6 not installed: {e}", file=sys.stderr)
        print("\nInstall with:", file=sys.stderr)
        print("  uv sync", file=sys.stderr)
        return 1

    return launch()


def main(argv: Sequence[str] | None = None) -> int:
    """Main entry point for the CLI.

    Args:
        argv: Command-line arguments (None = sys.argv[1:]).

    Returns:
        Exit code (0 for success, non-zero for failure).
    """
    parser = argparse.ArgumentParser(
        prog="cascade",
        description="A visual, pipeline-driven file manager that turns file operations into composable, repeatable workflows.",
    )
    parser.add_argument(
        "--version",
        action="version",
        version=f"%(prog)s {__version__}",
    )
    parser.add_argument(
        "--verbose",
        "-v",
        action="store_true",
        help="Enable verbose output",
    )

    subparsers = parser.add_subparsers(dest="command")
    summary_parser = subparsers.add_parser(
        "commit-summary",
        help="Render a commit summary payload using the shared API contract",
    )
    summary_parser.add_argument("--committed", type=int, default=0)
    summary_parser.add_argument("--skipped", type=int, default=0)
    summary_parser.add_argument("--failed", type=int, default=0)
    summary_parser.add_argument(
        "--json",
        action="store_true",
        dest="as_json",
        help="Print summary as JSON",
    )

    args = parser.parse_args(argv)

    if args.command == "commit-summary":
        result = CommitResult(
            committed=args.committed,
            skipped=args.skipped,
            failed=args.failed,
        )
        summary = CascadeAPI.format_commit_summary(result)

        if args.as_json:
            print(json.dumps(summary, sort_keys=True))
        else:
            print(summary["message"])
        return 0

    if args.verbose:
        print(f"Running {parser.prog} v{__version__}")

    # Launch native GUI
    return launch_gui()


if __name__ == "__main__":
    sys.exit(main())
