from __future__ import annotations

import argparse

from examples import (
    authenticate_github,
    download_example,
    download_examples,
    example_contents,
    example_readme,
    list_examples,
)


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="macroenergy-examples",
        description="Inspect and download examples from MacroEnergyExamples.jl.",
    )
    parser.add_argument(
        "--token",
        default=None,
        help="Optional GitHub token for authenticated API requests.",
    )

    subparsers = parser.add_subparsers(dest="command", required=True)

    list_parser = subparsers.add_parser("list", help="List available examples.")

    download_parser = subparsers.add_parser("download", help="Download one example.")
    download_parser.add_argument("name", help="Example name to download.")
    download_parser.add_argument("--target-dir", default=".", help="Download directory.")

    download_all_parser = subparsers.add_parser("download-all", help="Download all examples.")
    download_all_parser.add_argument("--target-dir", default=".", help="Download directory.")
    download_all_parser.add_argument(
        "--pause-seconds",
        type=float,
        default=1.0,
        help="Pause between downloads to avoid API rate limits.",
    )

    readme_parser = subparsers.add_parser("readme", help="Show README for one example.")
    readme_parser.add_argument("name", help="Example name.")

    contents_parser = subparsers.add_parser(
        "contents", help="List file paths for one example."
    )
    contents_parser.add_argument("name", help="Example name.")

    return parser


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()

    if args.token:
        auth = authenticate_github(args.token)
    else:
        auth = None

    if args.command == "list":
        list_examples(auth=auth)
        return 0

    if args.command == "download":
        download_example(
            args.name,
            target_dir=args.target_dir,
            auth=auth,
        )
        return 0

    if args.command == "download-all":
        download_examples(
            target_dir=args.target_dir,
            pause_seconds=args.pause_seconds,
            auth=auth,
        )
        return 0

    if args.command == "readme":
        example_readme(args.name, auth=auth)
        return 0

    if args.command == "contents":
        example_contents(args.name, auth=auth)
        return 0

    parser.error(f"Unknown command: {args.command}")
    return 2


if __name__ == "__main__":
    raise SystemExit(main())
