"""Generate mock CloudTrail logs for SCP simulation testing."""

import json
import sys
from pathlib import Path

import click

from ..generators.cloudtrail_generator import CloudTrailGenerator, GeneratorConfig


@click.command("generate-logs")
@click.option(
    "-o",
    "--output",
    "output_path",
    type=click.Path(),
    required=True,
    help="Output file path for generated CloudTrail logs",
)
@click.option(
    "-s",
    "--services",
    default="all",
    help="Comma-separated service prefixes or 'all' (default: all)",
)
@click.option(
    "-c",
    "--count",
    type=int,
    default=500,
    help="Total number of events to generate (default: 500)",
)
@click.option(
    "--regions",
    default="us-east-1,us-west-2,eu-west-1",
    help="Comma-separated AWS regions (default: us-east-1,us-west-2,eu-west-1)",
)
@click.option(
    "--account-id",
    default="123456789012",
    help="AWS account ID (default: 123456789012)",
)
@click.option(
    "--seed",
    type=int,
    default=None,
    help="Random seed for reproducible output",
)
@click.option(
    "--write-only",
    is_flag=True,
    help="Only include write/mutative operations (skip read/list)",
)
def generate_logs(
    output_path: str,
    services: str,
    count: int,
    regions: str,
    account_id: str,
    seed: int | None,
    write_only: bool,
) -> None:
    """Generate mock CloudTrail log events for SCP testing.

    Creates realistic CloudTrail events for any of the 442 AWS services
    in the IAM reference database. Events include proper requestParameters
    derived from IAM resource ARN patterns, ensuring high resource ARN
    resolution rates when used with `npkt simulate`.

    \b
    Examples:
      npkt generate-logs -o logs.json
      npkt generate-logs -o logs.json -s ec2,s3,iam -c 100
      npkt generate-logs -o logs.json --write-only --seed 42
      npkt generate-logs -o logs.json -c 1000 --regions us-east-1,eu-west-1
    """
    # Parse services
    service_list: list[str] | None = None
    if services.lower() != "all":
        service_list = [s.strip() for s in services.split(",") if s.strip()]

    # Parse regions
    region_list = [r.strip() for r in regions.split(",") if r.strip()]

    config = GeneratorConfig(
        services=service_list,
        count=count,
        regions=region_list,
        account_id=account_id,
        seed=seed,
        write_only=write_only,
    )

    generator = CloudTrailGenerator(config)
    click.echo("Generating CloudTrail events...", err=True)
    events = generator.generate()

    if not events:
        click.echo("No events generated. Check service names.", err=True)
        sys.exit(1)

    # Count unique services
    unique_services = len({e["eventSource"] for e in events})
    unique_actions = len({e["eventName"] for e in events})

    # Write output
    output = {"Records": events}
    out_path = Path(output_path)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    with open(out_path, "w", encoding="utf-8") as f:
        json.dump(output, f, indent=2)

    click.echo(
        f"Generated {len(events)} events across {unique_services} services "
        f"({unique_actions} unique actions)",
        err=True,
    )
    click.echo(f"Written to {out_path}", err=True)
    sys.exit(0)
