"""Command-line interface for gmailarchiver."""

import argparse
import sys
from pathlib import Path

from rich.console import Console

console = Console()


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        prog="gmailarchiver",
        description=(
            "Archive all Gmail messages from a given year to an mbox or Maildir "
            "file, then optionally remove them from your account."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
examples:
  # Archive 2022 to an mbox file, permanently delete from Gmail
  gmailarchiver 2022 --output ~/mail/2022.mbox

  # Archive 2021 to Maildir, move to Trash instead of hard-delete
  gmailarchiver 2021 --output ~/mail/2021/ --format maildir --trash

  # Dry run: count messages without downloading
  gmailarchiver 2020 --dry-run

  # Archive only; do NOT remove from Gmail
  gmailarchiver 2023 --output ~/mail/2023.mbox --no-delete

  # Use a non-default credentials file
  gmailarchiver 2022 --credentials ~/secrets/gmail_creds.json

setup:
  1. Create a Google Cloud project and enable the Gmail API.
  2. Create an OAuth 2.0 Desktop client and download credentials.json.
  3. Place credentials.json at ~/.gmailarchiver/credentials.json
     (or pass --credentials <path>).
  4. On first run a browser window opens for OAuth consent.
     The token is cached at ~/.gmailarchiver/token.json.
        """,
    )

    p.add_argument(
        "year",
        type=int,
        help="Calendar year to archive (e.g. 2022).",
    )
    p.add_argument(
        "--output", "-o",
        type=Path,
        default=None,
        help=(
            "Destination path. For mbox: a file path (e.g. ~/mail/2022.mbox). "
            "For maildir: a directory path. "
            "Defaults to ./<year>.mbox or ./<year>/ respectively."
        ),
    )
    p.add_argument(
        "--format", "-f",
        dest="fmt",
        choices=["mbox", "maildir"],
        default="mbox",
        help="Archive format (default: mbox).",
    )

    delete_grp = p.add_mutually_exclusive_group()
    delete_grp.add_argument(
        "--no-delete",
        action="store_true",
        help="Archive messages but do NOT remove them from Gmail.",
    )
    delete_grp.add_argument(
        "--trash",
        action="store_true",
        help=(
            "Move messages to Trash (recoverable for 30 days) "
            "instead of permanent deletion."
        ),
    )

    p.add_argument(
        "--dry-run",
        action="store_true",
        help="Count messages that would be archived; do nothing else.",
    )
    p.add_argument(
        "--credentials",
        type=Path,
        default=None,
        metavar="PATH",
        help="Path to credentials.json (default: ~/.gmailarchiver/credentials.json).",
    )
    p.add_argument(
        "--token",
        type=Path,
        default=None,
        metavar="PATH",
        help="Path to cached OAuth token (default: ~/.gmailarchiver/token.json).",
    )
    p.add_argument(
        "--label",
        action="append",
        dest="labels",
        metavar="LABEL_ID",
        help=(
            "Restrict to a Gmail label ID (can be repeated). "
            "Use 'INBOX', 'SENT', 'SPAM', 'TRASH', or a custom label ID. "
            "Default: all mail including spam/trash."
        ),
    )
    p.add_argument(
        "--version", "-V",
        action="version",
        version=f"%(prog)s {_version()}",
    )
    return p


def _version() -> str:
    from gmailarchiver import __version__
    return __version__


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)

    # Resolve output path default
    if args.output is None:
        args.output = Path(f"{args.year}.mbox" if args.fmt == "mbox" else str(args.year))

    # Validate year
    if args.year < 1970 or args.year > 2100:
        parser.error(f"Unreasonable year: {args.year}")

    # Lazy imports — keep startup fast
    try:
        from gmailarchiver.auth import get_service
        from gmailarchiver.archiver import run
    except ImportError as exc:
        console.print(f"[red]Import error: {exc}[/red]")
        console.print("Run: pip install gmailarchiver")
        return 1

    console.print(f"[bold]gmailarchiver[/bold] — year [cyan]{args.year}[/cyan]")

    # Authenticate
    try:
        service = get_service(
            credentials_path=args.credentials,
            token_path=args.token,
        )
    except FileNotFoundError as exc:
        console.print(f"[red]{exc}[/red]")
        return 1
    except Exception as exc:
        console.print(f"[red]Authentication failed: {exc}[/red]")
        return 1

    # Confirm destructive action
    if not args.no_delete and not args.dry_run:
        verb = "moved to Trash" if args.trash else "[bold red]permanently deleted[/bold red]"
        console.print(
            f"\n[yellow]Warning:[/yellow] Messages will be {verb} from your Gmail account "
            "after archiving."
        )
        try:
            confirm = input("Continue? [y/N] ").strip().lower()
        except (EOFError, KeyboardInterrupt):
            console.print("\nAborted.")
            return 0
        if confirm not in ("y", "yes"):
            console.print("Aborted.")
            return 0

    try:
        count = run(
            service=service,
            year=args.year,
            output=args.output,
            fmt=args.fmt,
            delete=not args.no_delete,
            trash=args.trash,
            dry_run=args.dry_run,
            label_ids=args.labels,
        )
    except KeyboardInterrupt:
        console.print("\n[yellow]Interrupted. Partial archive may exist on disk.[/yellow]")
        return 130
    except Exception as exc:
        console.print(f"[red]Fatal error: {exc}[/red]")
        return 1

    return 0


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