"""Billing management commands for AWS account cost passthrough via Stripe."""

import click

from ai_org.core.billing_manager import BillingManager


@click.group()
def billing() -> None:
    """Manage Stripe billing for AWS accounts."""


@billing.command()
@click.pass_context
def setup(ctx: click.Context) -> None:
    """One-time Stripe product setup.

    This will:
    1. Create a product in Stripe for AWS Infrastructure Services
    2. Create a price with monthly billing
    3. Display the product and price IDs for reference

    \b
    Example:
      ai-org billing setup
    """
    output = ctx.obj["output"]
    from ai_org.core.aws_client import AWSClient

    aws_client = AWSClient(
        profile=ctx.obj.get("profile"),
        region=ctx.obj.get("region"),
    )

    try:
        manager = BillingManager(aws_client)

        # Check which key we're using
        import os

        if os.getenv("TEST_STRIPE_SECRET_KEY"):
            output.info("Setting up Stripe products for AWS billing (TEST MODE)...")
            output.warning("Using TEST Stripe key - safe for testing")
        else:
            output.info("Setting up Stripe products for AWS billing...")
            if os.getenv("STRIPE_SECRET_KEY", "").startswith("sk_test_"):
                output.warning("Using TEST Stripe key - safe for testing")
            else:
                output.warning("Using PRODUCTION Stripe key - real charges will occur")

        result = manager.setup_stripe_products()

        output.success("\nStripe products created successfully!")
        output.info("\nProduct Details:")
        output.info(f"  Product ID: {result['product_id']}")
        output.info(f"  Price ID: {result['price_id']}")
        output.info("\nNext steps:")
        output.info("  1. Enable EventBridge integration in Stripe Dashboard")
        output.info(f"  2. AWS Account ID for EventBridge: {aws_client.account_id}")
        output.info("  3. Select region: us-east-1")
        output.info("  4. Link AWS accounts to Stripe customers using 'ai-org billing link'")

        if ctx.obj.get("json_output"):
            output.print_json(result)

    except Exception as e:
        output.error(f"Failed to setup Stripe products: {e}")
        ctx.exit(1)


@billing.command()
@click.argument("account_id")
@click.argument("stripe_customer_id")
@click.pass_context
def link(ctx: click.Context, account_id: str, stripe_customer_id: str) -> None:
    """Link AWS account to Stripe customer.

    \b
    Arguments:
      ACCOUNT_ID          AWS account ID to link
      STRIPE_CUSTOMER_ID  Stripe customer ID (e.g., cus_xxx)

    \b
    Example:
      ai-org billing link 123456789012 cus_AbCdEfGhIjKl

    This creates a mapping in DynamoDB that the Lambda function will use
    to calculate and bill AWS costs for this account to the Stripe customer.
    """
    output = ctx.obj["output"]
    from ai_org.core.aws_client import AWSClient

    aws_client = AWSClient(
        profile=ctx.obj.get("profile"),
        region=ctx.obj.get("region"),
    )

    try:
        manager = BillingManager(aws_client)

        # Validate account ID format
        if not account_id.isdigit() or len(account_id) != 12:
            output.error(f"Invalid AWS account ID format: {account_id}")
            output.info("Account ID must be 12 digits")
            ctx.exit(1)

        # Validate Stripe customer ID format
        if not stripe_customer_id.startswith("cus_"):
            output.error(f"Invalid Stripe customer ID format: {stripe_customer_id}")
            output.info("Stripe customer ID should start with 'cus_'")
            ctx.exit(1)

        output.info(f"Linking AWS account {account_id} to Stripe customer {stripe_customer_id}...")

        manager.link_account(account_id, stripe_customer_id)

        output.success(
            f"\nSuccessfully linked account {account_id} to customer {stripe_customer_id}"
        )
        output.info("\nBilling will begin with the next invoice cycle.")

        if ctx.obj.get("json_output"):
            output.print_json(
                {
                    "account_id": account_id,
                    "stripe_customer_id": stripe_customer_id,
                    "status": "linked",
                }
            )

    except Exception as e:
        output.error(f"Failed to link account: {e}")
        ctx.exit(1)


@billing.command("list")
@click.pass_context
def list_mappings(ctx: click.Context) -> None:
    """List all AWS account to Stripe customer mappings.

    \b
    Example:
      ai-org billing list

    Shows all configured billing relationships between AWS accounts
    and Stripe customers.
    """
    output = ctx.obj["output"]
    from ai_org.core.aws_client import AWSClient

    aws_client = AWSClient(
        profile=ctx.obj.get("profile"),
        region=ctx.obj.get("region"),
    )

    try:
        manager = BillingManager(aws_client)
        output.info("Fetching billing mappings...")

        mappings = manager.list_mappings()

        if not mappings:
            output.info("\nNo billing mappings configured.")
            output.info("Use 'ai-org billing link' to add mappings.")
        else:
            output.info(f"\nFound {len(mappings)} billing mapping(s):\n")

            if ctx.obj.get("json_output"):
                output.json_output(mappings)
            else:
                # Format for table display
                table_data = []
                for mapping in mappings:
                    table_data.append(
                        {
                            "Stripe Customer": mapping["stripe_customer_id"],
                            "AWS Accounts": ", ".join(mapping.get("aws_accounts", [])),
                            "Created": mapping.get("created_at", "Unknown"),
                        }
                    )

                output.table(
                    table_data,
                    columns=["Stripe Customer", "AWS Accounts", "Created"],
                    title="Billing Mappings",
                )

    except Exception as e:
        output.error(f"Failed to list mappings: {e}")
        ctx.exit(1)


@billing.command()
@click.argument("account_id")
@click.pass_context
def unlink(ctx: click.Context, account_id: str) -> None:
    """Remove AWS account from billing.

    \b
    Arguments:
      ACCOUNT_ID  AWS account ID to unlink

    \b
    Example:
      ai-org billing unlink 123456789012

    This removes the account from billing. The account will not be
    included in future invoices.
    """
    output = ctx.obj["output"]
    from ai_org.core.aws_client import AWSClient

    aws_client = AWSClient(
        profile=ctx.obj.get("profile"),
        region=ctx.obj.get("region"),
    )

    try:
        manager = BillingManager(aws_client)

        # Validate account ID format
        if not account_id.isdigit() or len(account_id) != 12:
            output.error(f"Invalid AWS account ID format: {account_id}")
            output.info("Account ID must be 12 digits")
            ctx.exit(1)

        output.info(f"Unlinking AWS account {account_id} from billing...")

        manager.unlink_account(account_id)

        output.success(f"\nSuccessfully unlinked account {account_id} from billing")

        if ctx.obj.get("json_output"):
            output.print_json({"account_id": account_id, "status": "unlinked"})

    except Exception as e:
        output.error(f"Failed to unlink account: {e}")
        ctx.exit(1)
