#!/usr/bin/env python3
"""List Gitea issues.

Usage:
    list_issues.py --remote dadeschools
"""
import os
import sys
import argparse

# Auto-execute using the project's local virtual environment Python
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
venv_python = os.path.join(PROJECT_ROOT, "venv", "bin", "python3")
if os.path.exists(venv_python) and sys.executable != venv_python:
    os.execv(venv_python, [venv_python] + sys.argv)

from gitea_auth import get_auth_header, resolve_remote, add_remote_args, api_request, repo_api_url


def main(argv=None):
    parser = argparse.ArgumentParser(description="List Gitea issues.")
    add_remote_args(parser)
    parser.add_argument("--state", choices=["open", "closed", "all"], default="open",
                        help="Filter by issue state (default: open).")
    parser.add_argument("--label", help="Filter by label name.")
    args = parser.parse_args(argv)

    host, org, repo = resolve_remote(args)
    auth = get_auth_header(host)
    if not auth:
        print(f"Could not get credentials or token for {host}.", file=sys.stderr)
        return 1

    params = f"state={args.state}&type=issues"
    if args.label:
        params += f"&labels={args.label}"
    url = f"{repo_api_url(host, org, repo)}/issues?{params}"

    try:
        issues = api_request("GET", url, auth)
        if not issues:
            print("No issues found.")
            return 0

        for i in issues:
            labels_str = ", ".join(lb["name"] for lb in i.get("labels", []))
            labels_part = f" [{labels_str}]" if labels_str else ""
            assignee = (i.get("assignee") or {}).get("login", "unassigned")
            print(f"Issue #{i['number']}: {i['title']}{labels_part}")
            print(f"  State: {i['state']} | Assignee: {assignee}")
            print(f"  URL: {i['html_url']}")
        return 0
    except Exception as e:
        print(f"Error listing issues: {e}", file=sys.stderr)
        return 1


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