# Copyright 2026 4f4d
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Command-line interface for f1radio."""

from __future__ import annotations

import argparse
import sys


def _cmd_download(args: argparse.Namespace) -> None:
    """Download and cache a session."""
    import f1radio

    print(f"Loading {args.year} {args.race} ({args.session})...")
    try:
        session = f1radio.load(
            year=args.year,
            race=args.race,
            session=args.session,
            verbose=True,
            force_refresh=args.force,
        )
        print(f"\n✓ {session}")
        print(f"  {len(session.clips)} clips from {len(session.drivers)} drivers")
        if session.driver_counts:
            top = list(session.driver_counts.items())[:5]
            top_str = ", ".join(f"{d} ({n})" for d, n in top)
            print(f"  Most active: {top_str}")
    except Exception as e:
        print(f"✗ Error: {e}", file=sys.stderr)
        sys.exit(1)


def _cmd_info(args: argparse.Namespace) -> None:
    """Show session info (from cache if available)."""
    import f1radio

    try:
        session = f1radio.load(
            year=args.year,
            race=args.race,
            session=args.session,
            verbose=False,
        )
        print(session)
        print(f"  Clips: {len(session.clips)}")
        print(f"  Drivers: {', '.join(session.drivers)}")
        if session.time_range:
            print(f"  Time range: {session.time_range[0]} → {session.time_range[1]}")
        if session.driver_counts:
            print("  Clip counts:")
            for driver, count in session.driver_counts.items():
                print(f"    {driver}: {count}")
    except Exception as e:
        print(f"✗ Error: {e}", file=sys.stderr)
        sys.exit(1)


def _cmd_cache_list(args: argparse.Namespace) -> None:
    """List cached sessions."""
    import f1radio

    info = f1radio.cache_info()
    if not info["sessions"]:
        print("No cached sessions.")
        return

    print(f"Cache directory: {info['cache_dir']}")
    print(f"Total size: {info['total_size_mb']} MB")
    print()
    for name, details in info["sessions"].items():
        print(f"  {name}")
        print(f"    Size: {details['size_mb']} MB | MP3s: {details['mp3_count']}")


def _cmd_cache_clear(args: argparse.Namespace) -> None:
    """Clear cache."""
    import f1radio

    count = f1radio.clear_cache()
    if count > 0:
        print(f"✓ Cleared {count} cached session(s)")
    else:
        print("Cache is already empty")


def main(argv: list[str] | None = None) -> None:
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        prog="f1radio",
        description="📻 F1 team radio clips enriched with race context",
    )
    parser.add_argument(
        "--version",
        action="version",
        version="f1radio 1.0.0",
    )

    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # download
    dl_parser = subparsers.add_parser(
        "download",
        help="Download and cache a session",
    )
    dl_parser.add_argument("year", type=int, help="Season year (e.g., 2024)")
    dl_parser.add_argument("race", help='Race name (e.g., "Monza", "Italian")')
    dl_parser.add_argument(
        "session",
        nargs="?",
        default="R",
        help="Session type: R, Q, FP1, FP2, FP3, S, SQ (default: R)",
    )
    dl_parser.add_argument(
        "--force", "-f",
        action="store_true",
        help="Force re-download even if cached",
    )

    # info
    info_parser = subparsers.add_parser(
        "info",
        help="Show session info",
    )
    info_parser.add_argument("year", type=int)
    info_parser.add_argument("race")
    info_parser.add_argument("session", nargs="?", default="R")

    # cache
    cache_parser = subparsers.add_parser(
        "cache",
        help="Manage local cache",
    )
    cache_sub = cache_parser.add_subparsers(dest="cache_command")
    cache_sub.add_parser("list", help="List cached sessions")
    cache_sub.add_parser("clear", help="Clear all cached data")

    args = parser.parse_args(argv)

    if args.command is None:
        parser.print_help()
        sys.exit(0)

    if args.command == "download":
        _cmd_download(args)
    elif args.command == "info":
        _cmd_info(args)
    elif args.command == "cache":
        if args.cache_command == "list":
            _cmd_cache_list(args)
        elif args.cache_command == "clear":
            _cmd_cache_clear(args)
        else:
            cache_parser.print_help()
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
