import argparse
import os
import sys
from collections.abc import Sequence

from ._client import AccountResult, CasaGeoClient
from ._errors import CasaGeoError
from ._types import CasaGeoResult

__all__ = [
    "AccountResult",
    "CasaGeoClient",
    "CasaGeoError",
    "CasaGeoResult",
]


def _accountinfo_command(client: CasaGeoClient, options: argparse.Namespace) -> None:
    result = client.account_info() or sys.exit(1)
    result.dataframe(
        id_=options.with_id,
    ).to_csv(sys.stdout, sep=";", index=False)


def _main(args: Sequence[str] | None = None) -> None:
    parser = argparse.ArgumentParser(
        description="Commands for interacting with the casaGeo API",
        allow_abbrev=False,
    )
    subparsers = parser.add_subparsers(
        title="subcommands",
        required=True,
        metavar="COMMAND",
    )

    # Account Info Subcommand

    accountinfo_parser = subparsers.add_parser(
        "account-info",
        help="query the server for account information",
        description="Query the server for account information.",
    )
    accountinfo_parser.set_defaults(command=_accountinfo_command)

    accountinfo_dfparams = accountinfo_parser.add_argument_group(
        title="dataframe parameters",
    )
    accountinfo_dfparams.add_argument(
        "--with-id",
        help="sets the value of the id column",
        metavar="ID",
    )

    # Main Function Body

    options = parser.parse_args(args)
    api_key = os.getenv("CASAGEOTOOLS_API_KEY") or sys.exit(
        "Please specify an API key in the environment variable CASAGEOTOOLS_API_KEY"
    )

    options.command(CasaGeoClient(api_key), options)
