import argparse
import sys

import requests
from colorama import Fore, Style
from rich.console import Console
from rich.table import Table

TEMPLATES_REPO = "pyfenn/templates"
REPO_NAME = "templates"
GITHUB_API_BASE = "https://api.github.com"
GITHUB_ARCHIVE_BASE = "https://github.com"


def execute(args: argparse.Namespace) -> None:
    """
    Execute the fenn list command, to show all accessible templates.
    """
    try:
        _list_templates()
    except NetworkError as e:
        print(f"{Fore.RED}Network error: {e}{Style.RESET_ALL}")
        sys.exit(1)


class NetworkError(Exception):
    """Raised when a network request fails."""

    pass


def _list_templates() -> None:
    """
    List all available template directories in the templates repository.

    Raises:
        NetworkError: If network request fails
    """
    api_url = f"{GITHUB_API_BASE}/repos/{TEMPLATES_REPO}/contents"

    try:
        response = requests.get(api_url, timeout=10)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        raise NetworkError(f"Failed to fetch template list: {e}")

    contents = response.json()

    templates = [item["name"] for item in contents if item.get("type") == "dir"]

    if not templates:
        print(f"{Fore.YELLOW}No templates found in the repository.{Style.RESET_ALL}")
        return

    templates.sort()

    console = Console()
    table = Table(title="")
    table.add_column("Available templates", style="", width=50)
    for template in templates:
        if not template.endswith("dev-only"):
            table.add_row(f"- {template}")
    console.print(table)
    console.print(
        "[cyan]Use [yellow]fenn pull <template>[/yellow] to download a template.[/cyan]"
    )
