from __future__ import annotations

import argparse
import os
from typing import Optional

from .engine import AzurePolicyEngine
from . import cli_handlers


def _load_azure_credential() -> Optional[object]:
    try:
        from azure.identity import DefaultAzureCredential

        return DefaultAzureCredential()
    except Exception:
        return None


def main(argv=None):
    p = argparse.ArgumentParser(prog="azure-policy-engine")
    p.add_argument(
        "--backend",
        default=os.environ.get("AZPE_BACKEND", "file"),
        choices=["file", "sdk", "azcli"],
    )
    p.add_argument("--policies-dir", default=os.environ.get("AZPE_POLICY_DIR"))
    p.add_argument("--subscription-id", default=os.environ.get("AZPE_SUBSCRIPTION_ID"))
    sub = p.add_subparsers(dest="cmd")

    sub.add_parser("list")
    g = sub.add_parser("get")
    g.add_argument("name")
    d = sub.add_parser("deploy")
    d.add_argument("name")
    d.add_argument("file")
    sub.add_parser("assignments")
    ca = sub.add_parser("create-assignment")
    ca.add_argument("name")
    ca.add_argument("file")
    ua = sub.add_parser("update-assignment")
    ua.add_argument("name")
    ua.add_argument("file")
    da = sub.add_parser("delete-assignment")
    da.add_argument("name")
    sub.add_parser("compliance")
    a = sub.add_parser("add-assignment")
    a.add_argument("name")
    a.add_argument("file")
    ai = sub.add_parser("assign-initiative")
    ai.add_argument("initiative-name")
    ai.add_argument("assignment-name")
    ai.add_argument("file")
    i = sub.add_parser("list-initiatives")
    i.add_argument("--raw", action="store_true")
    p.add_argument(
        "--scope",
        default=None,
        help="Scope for assignments (e.g. /subscriptions/.. or /providers/Microsoft.Management/managementGroups/{id})",
    )
    p.add_argument(
        "--mgmt-group",
        dest="mgmt_group",
        default=None,
        help="Management group id (shorthand); builds scope /providers/Microsoft.Management/managementGroups/{id}",
    )
    p.add_argument(
        "--dry-run",
        dest="dry_run",
        action="store_true",
        help="Do not perform changes; print the effective payload and scope",
    )

    args = p.parse_args(argv)
    credential = _load_azure_credential() if args.backend == "sdk" else None
    engine = AzurePolicyEngine(
        backend=args.backend,
        policy_dir=args.policies_dir,
        subscription_id=args.subscription_id,
        credential=credential,
    )

    # Delegate command handling to the handlers module which keeps `main` simple.
    cli_handlers.handle_command(args, engine)


if __name__ == "__main__":
    main()
