"""
zones.py — AWS skill pack zones for NEXUS.
"""

from engine.zone import Zone
from engine.challenge import Challenge

ZONE_ORDER = [
    "iam_and_security",
    "ec2_and_compute",
    "s3_and_storage",
    "vpc_and_networking",
    "rds_and_databases",
    "lambda_and_serverless",
    "cloudwatch_and_monitoring",
    "cloudformation_and_iac",
    "ecs_and_containers",
    "elb_and_autoscaling",
    "route53_and_cdn",
]

ZONES = {
    "iam_and_security": Zone(
        id="iam_and_security",
        title="IAM and Security",
        description="Manage identities, roles, policies, and access controls in AWS.",
        challenges=[
            Challenge(
                id="aws_iam_principle",
                type="quiz",
                prompt="The principle of least privilege in AWS IAM means:",
                options=[
                    "Give all developers AdministratorAccess for convenience",
                    "Grant only the permissions needed to perform a specific function",
                    "Rotate all passwords every 24 hours",
                    "Use a single shared IAM user for the team",
                ],
                answer="b",
                explanation="Least privilege minimizes blast radius. A compromised key with S3 read-only cannot launch EC2 instances; one with AdministratorAccess can destroy your entire AWS account.",
                url="https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html",
                xp=10,
            ),
            Challenge(
                id="aws_iam_role_vs_user",
                type="quiz",
                prompt="An EC2 instance needs to access an S3 bucket. The correct approach is:",
                options=[
                    "Hardcode AWS access keys in the application code",
                    "Create an IAM user and put the credentials in an env file on the instance",
                    "Attach an IAM Role with the required S3 permissions to the EC2 instance",
                    "Make the S3 bucket public",
                ],
                answer="c",
                explanation="IAM Roles provide temporary credentials via the instance metadata service — no long-lived keys to manage, rotate, or accidentally expose. This is the AWS-recommended pattern.",
                xp=10,
            ),
            Challenge(
                id="aws_iam_policy_type",
                type="quiz",
                prompt="What is the difference between an AWS Managed Policy and a Customer Managed Policy?",
                options=[
                    "Managed policies are free; customer policies cost extra",
                    "AWS manages and updates AWS Managed Policies; you control Customer Managed Policies",
                    "Managed policies apply cluster-wide; customer policies are region-specific",
                    "There is no functional difference",
                ],
                answer="b",
                explanation="AWS Managed Policies (like AmazonS3ReadOnlyAccess) are maintained by AWS and updated as services evolve. Customer Managed Policies give you full control over permissions with versioning.",
                xp=10,
            ),
            Challenge(
                id="aws_mfa",
                type="fill_blank",
                prompt="The AWS security best practice for the root account is to enable _____ (abbreviated) and never use it for daily tasks.",
                answer="MFA",
                explanation="The AWS root account has unrestricted access to all services. Enable MFA, create IAM users for daily use, and lock root credentials away. A compromised root account cannot be restricted.",
                xp=15,
                hints=["Multi-Factor Authentication"],
            ),
            Challenge(
                id="aws_sts",
                type="quiz",
                prompt="AWS STS (Security Token Service) is used for:",
                options=[
                    "Storing secrets like database passwords",
                    "Issuing temporary, limited-privilege credentials for IAM roles",
                    "Scanning S3 buckets for malware",
                    "Monitoring API calls across all AWS services",
                ],
                answer="b",
                explanation="STS issues temporary credentials (access key, secret key, session token) that expire automatically. AssumeRole uses STS — when an EC2 instance assumes a role, it gets STS credentials.",
                xp=10,
            ),
            Challenge(
                id="aws_cloudtrail",
                type="quiz",
                prompt="AWS CloudTrail records:",
                options=[
                    "CPU and memory metrics for EC2 instances",
                    "All API calls made to AWS services — who did what, when, from where",
                    "Network traffic between VPC subnets",
                    "Application logs from Lambda functions",
                ],
                answer="b",
                explanation="CloudTrail is the audit log for your AWS account. Every API call — `CreateInstance`, `DeleteBucket`, `AssumeRole` — is recorded with the caller identity, time, and source IP. Essential for security investigations.",
                xp=15,
                hints=["Think 'audit trail'"],
            ),
        ],
    ),
    "ec2_and_compute": Zone(
        id="ec2_and_compute",
        title="EC2 and Compute",
        description="Launch, configure, and manage virtual machines in the AWS cloud.",
        challenges=[
            Challenge(
                id="aws_ec2_ami",
                type="quiz",
                prompt="An AMI (Amazon Machine Image) is:",
                options=[
                    "A virtual network interface for EC2 instances",
                    "A template containing an OS, application, and configuration for launching EC2 instances",
                    "An encrypted storage volume attached to an instance",
                    "A load balancer configuration",
                ],
                answer="b",
                explanation="An AMI is a pre-configured snapshot: OS + software + config. You launch instances from AMIs. They enable repeatability — every instance from the same AMI starts in the same known state.",
                url="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html",
                xp=10,
            ),
            Challenge(
                id="aws_ec2_instance_types",
                type="quiz",
                prompt="An EC2 instance type like `t3.medium` encodes what information?",
                options=[
                    "The AWS region and availability zone",
                    "The instance family (t=burstable) and size (medium) — CPU/memory ratio",
                    "The storage type and network throughput",
                    "The pricing tier and support level",
                ],
                answer="b",
                explanation="Instance types encode family (t=burstable, c=compute-optimized, m=general, r=memory-optimized) and size. `t3.medium` has 2 vCPU and 4 GiB RAM; `c5.2xlarge` has 8 vCPU and 16 GiB RAM.",
                xp=10,
            ),
            Challenge(
                id="aws_security_groups",
                type="quiz",
                prompt="AWS Security Groups are:",
                options=[
                    "Firewall rules for entire VPCs",
                    "Stateful virtual firewalls that control inbound and outbound traffic to EC2 instances",
                    "Groups of IAM users with shared permissions",
                    "Network ACLs applied at the subnet level",
                ],
                answer="b",
                explanation="Security Groups are stateful — if you allow inbound port 443, the response traffic is automatically allowed outbound. They apply to instances (not subnets, which is NACLs). Default: deny all inbound, allow all outbound.",
                xp=10,
            ),
            Challenge(
                id="aws_key_pairs",
                type="fill_blank",
                prompt="To SSH into an EC2 Linux instance, you authenticate using a key _____. AWS stores the public key; you keep the private key.",
                answer="pair",
                explanation="EC2 key pairs use asymmetric cryptography. AWS injects the public key into the instance at launch; you use the private key file (.pem) to authenticate. If you lose the private key, you lose SSH access.",
                xp=15,
                hints=["Two keys — one public, one private"],
            ),
            Challenge(
                id="aws_user_data",
                type="quiz",
                prompt="EC2 User Data is a script that runs:",
                options=[
                    "Continuously in the background while the instance runs",
                    "Once at first instance launch to bootstrap configuration",
                    "Every time the instance restarts",
                    "On a schedule defined in CloudWatch Events",
                ],
                answer="b",
                explanation="User Data runs once at first launch as root. Use it to install packages, pull code from S3, configure services — bootstrap automation without a configuration management tool.",
                xp=10,
            ),
            Challenge(
                id="aws_elastic_ip",
                type="quiz",
                prompt="Why does a stopped and restarted EC2 instance get a different public IP?",
                options=[
                    "AWS assigns IPs from DHCP which expires on stop",
                    "AWS charges per IP so it reallocates them",
                    "Public IPs are dynamic by default; Elastic IPs are static and must be explicitly allocated",
                    "The instance moves to a different availability zone",
                ],
                answer="c",
                explanation="Public IPs are dynamic — released when an instance stops, reassigned when it starts. An Elastic IP is a static IPv4 address you allocate and associate with an instance, surviving stop/start cycles.",
                xp=15,
                hints=["There's a product called 'Elastic IP' for a reason"],
            ),
        ],
    ),
    "s3_and_storage": Zone(
        id="s3_and_storage",
        title="S3 and Storage",
        description="Store and retrieve any amount of data using Amazon Simple Storage Service.",
        challenges=[
            Challenge(
                id="aws_s3_bucket",
                type="quiz",
                prompt="S3 bucket names must be globally unique because:",
                options=[
                    "AWS limits each account to 100 buckets",
                    "Bucket names are used in the bucket's URL, which must be globally unique",
                    "All S3 buckets share a single partition key",
                    "AWS charges per name uniqueness check",
                ],
                answer="b",
                explanation="Bucket URLs follow the pattern `bucket-name.s3.amazonaws.com`. Since URLs must be unique globally, so must bucket names. This is why `my-bucket` is likely taken — use unique prefixes.",
                url="https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html",
                xp=10,
            ),
            Challenge(
                id="aws_s3_storage_classes",
                type="quiz",
                prompt="Which S3 storage class is cheapest for data accessed once every few years?",
                options=["S3 Standard", "S3 Intelligent-Tiering", "S3 Glacier Deep Archive", "S3 One Zone-IA"],
                answer="c",
                explanation="S3 Glacier Deep Archive is the lowest-cost S3 storage, designed for data retained for compliance that's rarely accessed. Retrieval time: 12 hours. Use Standard for frequent access, IA for infrequent, Glacier for archival.",
                xp=10,
            ),
            Challenge(
                id="aws_s3_versioning",
                type="quiz",
                prompt="With S3 versioning enabled, deleting an object:",
                options=[
                    "Permanently removes the object and all versions",
                    "Adds a delete marker — previous versions remain and can be restored",
                    "Moves the object to S3 Glacier automatically",
                    "Requires MFA confirmation",
                ],
                answer="b",
                explanation="Versioning inserts a delete marker rather than actually deleting. All previous versions survive. To permanently delete, you must delete each version explicitly (or use lifecycle policies).",
                xp=10,
            ),
            Challenge(
                id="aws_s3_presigned",
                type="fill_blank",
                prompt="To give a user temporary access to a private S3 object without making it public, generate a _____ URL.",
                answer="presigned",
                explanation="Presigned URLs embed temporary credentials that allow accessing a specific object. They expire after a set time and work without AWS credentials on the client side — perfect for sharing private content.",
                xp=15,
                hints=["You're signing the URL in advance", "Pre + signed"],
            ),
            Challenge(
                id="aws_s3_lifecycle",
                type="quiz",
                prompt="An S3 lifecycle rule can automatically:",
                options=[
                    "Scan objects for malware",
                    "Transition objects to cheaper storage classes or expire (delete) them after set periods",
                    "Replicate objects to on-premises storage",
                    "Compress objects to reduce storage costs",
                ],
                answer="b",
                explanation="Lifecycle rules automate cost management. Example: move to IA after 30 days → Glacier after 90 days → delete after 365 days. No manual intervention needed.",
                xp=10,
            ),
            Challenge(
                id="aws_s3_public_block",
                type="quiz",
                prompt="AWS S3 Block Public Access is a setting that:",
                options=[
                    "Prevents outbound S3 transfers above a threshold",
                    "Blocks all public access to buckets regardless of bucket policies or ACLs",
                    "Requires HTTPS for all S3 requests",
                    "Enables encryption on all new objects",
                ],
                answer="b",
                explanation="Block Public Access overrides bucket policies and ACLs — even if a bucket policy grants public access, Block Public Access will deny it. Enable at the account level as a default-secure baseline.",
                xp=15,
                hints=["It's a blanket override, not another policy"],
            ),
        ],
    ),
    "vpc_and_networking": Zone(
        id="vpc_and_networking",
        title="VPC and Networking",
        description="Design and configure isolated networks in AWS with subnets, routing, and gateways.",
        challenges=[
            Challenge(
                id="aws_vpc_definition",
                type="quiz",
                prompt="A VPC (Virtual Private Cloud) provides:",
                options=[
                    "A managed Kubernetes cluster in AWS",
                    "An isolated, logically separated network in AWS where you control IP ranges and routing",
                    "A CDN for distributing content globally",
                    "A VPN connection to your on-premises network",
                ],
                answer="b",
                explanation="A VPC is your own isolated section of the AWS cloud. You control the IP range (CIDR block), subnets, route tables, and internet/NAT gateways. Resources inside a VPC are isolated from other AWS customers.",
                url="https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html",
                xp=10,
            ),
            Challenge(
                id="aws_public_private_subnet",
                type="quiz",
                prompt="The difference between a public and private subnet in AWS is:",
                options=[
                    "Public subnets have more IP addresses than private ones",
                    "A public subnet has a route to an Internet Gateway; a private subnet does not",
                    "Private subnets require a VPN to access",
                    "Public subnets are accessible from other VPCs by default",
                ],
                answer="b",
                explanation="Subnets are public or private based on routing: if there's a route `0.0.0.0/0 → igw-xxxx` in the route table, it's public. Private subnets route outbound traffic through a NAT Gateway instead.",
                xp=10,
            ),
            Challenge(
                id="aws_nat_gateway",
                type="quiz",
                prompt="A NAT Gateway allows instances in private subnets to:",
                options=[
                    "Receive inbound connections from the internet",
                    "Connect to other VPCs without internet exposure",
                    "Initiate outbound internet connections without being directly accessible from the internet",
                    "Bypass security group rules",
                ],
                answer="c",
                explanation="NAT (Network Address Translation) Gateway translates private IPs to its own public IP for outbound traffic. Private instances can download updates, call APIs — but nothing on the internet can initiate a connection to them.",
                xp=10,
            ),
            Challenge(
                id="aws_cidr",
                type="fill_blank",
                prompt="A VPC with CIDR block `10.0.0.0/16` has _____ available IP addresses.",
                answer="65536",
                explanation="A /16 CIDR has 2^(32-16) = 2^16 = 65,536 IP addresses. AWS reserves 5 per subnet. /16 is a common VPC size; subnets are typically /24 (256 addresses) carved from it.",
                xp=15,
                hints=["2 raised to the power of (32 minus 16)"],
            ),
            Challenge(
                id="aws_security_group_vs_nacl",
                type="quiz",
                prompt="The key difference between Security Groups and Network ACLs (NACLs) is:",
                options=[
                    "Security Groups are free; NACLs are paid",
                    "Security Groups are stateful (per-instance); NACLs are stateless (per-subnet)",
                    "NACLs apply to EC2 only; Security Groups apply to all services",
                    "Security Groups deny by default; NACLs allow by default",
                ],
                answer="b",
                explanation="Security Groups are stateful — track connections, auto-allow responses. NACLs are stateless — evaluate every packet independently, applied at subnet level. NACLs need explicit allow rules for both inbound and return traffic.",
                xp=15,
                hints=["One is stateful, one is stateless"],
            ),
            Challenge(
                id="aws_vpc_peering",
                type="quiz",
                prompt="VPC Peering connects two VPCs so that traffic routes between them:",
                options=[
                    "Via the public internet, encrypted with TLS",
                    "Using the AWS private network backbone — not through the internet",
                    "Through a VPN tunnel that must be manually configured",
                    "Only if both VPCs are in the same AWS account",
                ],
                answer="b",
                explanation="VPC Peering routes traffic privately within AWS. No internet exposure, no bandwidth bottleneck. Limitation: peering is non-transitive — if A peers with B and B peers with C, A cannot reach C through B.",
                xp=10,
            ),
        ],
    ),
    "rds_and_databases": Zone(
        id="rds_and_databases",
        title="RDS and Databases",
        description="Deploy and manage relational databases with Amazon RDS.",
        challenges=[
            Challenge(
                id="aws_rds_purpose",
                type="quiz",
                prompt="Amazon RDS (Relational Database Service) manages:",
                options=[
                    "NoSQL document storage for flexible schemas",
                    "Relational databases with automated backups, patching, and failover",
                    "In-memory caching with Redis and Memcached",
                    "Data warehousing for analytical workloads",
                ],
                answer="b",
                explanation="RDS handles the undifferentiated heavy lifting: OS patching, backups, replication, failover. You focus on the database schema and queries; AWS handles the infrastructure operations.",
                url="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html",
                xp=10,
            ),
            Challenge(
                id="aws_rds_multi_az",
                type="quiz",
                prompt="RDS Multi-AZ deployments provide:",
                options=[
                    "Horizontal read scaling across multiple availability zones",
                    "Automatic failover to a standby replica in a different AZ if the primary fails",
                    "Lower storage costs by distributing data across zones",
                    "Global replication to multiple AWS regions",
                ],
                answer="b",
                explanation="Multi-AZ maintains a synchronous standby in a different AZ. If the primary fails, RDS automatically promotes the standby — typically in 60-120 seconds. This is for HA, not read scaling (that's Read Replicas).",
                xp=10,
            ),
            Challenge(
                id="aws_rds_read_replica",
                type="quiz",
                prompt="An RDS Read Replica is used for:",
                options=[
                    "Disaster recovery with automatic failover",
                    "Offloading read queries to improve primary database performance",
                    "Synchronous replication to prevent data loss",
                    "Database encryption at rest",
                ],
                answer="b",
                explanation="Read Replicas use asynchronous replication (slight lag). Direct heavy read traffic (reports, analytics) to replicas to reduce load on the primary. They cannot handle writes and are not automatic failover targets (by default).",
                xp=10,
            ),
            Challenge(
                id="aws_rds_parameter_groups",
                type="fill_blank",
                prompt="To change database engine settings like `max_connections` in RDS, you modify a _____  group.",
                answer="parameter",
                explanation="RDS Parameter Groups contain engine configuration settings. You can't SSH into an RDS instance to edit config files — instead, create a custom parameter group, set your values, and apply it to the RDS instance.",
                xp=15,
                hints=["It's a group of configuration parameters"],
            ),
            Challenge(
                id="aws_rds_backup",
                type="quiz",
                prompt="RDS automated backups allow you to restore to:",
                options=[
                    "Only the last daily backup snapshot",
                    "Any point in time within the backup retention period (up to 35 days)",
                    "A different database engine version",
                    "An on-premises server",
                ],
                answer="b",
                explanation="RDS keeps transaction logs in addition to daily snapshots, enabling point-in-time recovery. Set `backup_retention_period` to 1-35 days. The default is 7 days — set it to 35 for production databases.",
                xp=10,
            ),
            Challenge(
                id="aws_rds_encryption",
                type="quiz",
                prompt="You cannot enable encryption at rest on an existing unencrypted RDS instance. The correct migration path is:",
                options=[
                    "Upgrade the instance to a larger size which enables encryption",
                    "Take a snapshot, copy the snapshot with encryption enabled, restore from the encrypted snapshot",
                    "Enable the `storage_encrypted` parameter in the parameter group",
                    "Run `ALTER DATABASE ... ENCRYPT` in the database engine",
                ],
                answer="b",
                explanation="Encryption can only be enabled at creation time. To encrypt an existing database: take snapshot → copy with encryption → restore. Plan encryption upfront for production databases.",
                xp=15,
                hints=["Snapshots can be copied with different settings"],
            ),
        ],
    ),
    "lambda_and_serverless": Zone(
        id="lambda_and_serverless",
        title="Lambda and Serverless",
        description="Run code without managing servers using AWS Lambda functions.",
        challenges=[
            Challenge(
                id="aws_lambda_definition",
                type="quiz",
                prompt="AWS Lambda is a compute service that:",
                options=[
                    "Manages containerized workloads on dedicated EC2 instances",
                    "Runs code in response to events without provisioning or managing servers",
                    "Provides a managed Kubernetes cluster",
                    "Hosts virtual machines on AWS bare metal",
                ],
                answer="b",
                explanation="Lambda is event-driven serverless compute. You write functions; AWS provisions infrastructure, scales automatically, and charges per 100ms of execution. No servers to patch, no capacity to plan.",
                url="https://docs.aws.amazon.com/lambda/latest/dg/welcome.html",
                xp=10,
            ),
            Challenge(
                id="aws_lambda_triggers",
                type="quiz",
                prompt="Which of these can trigger a Lambda function?",
                options=[
                    "Only HTTP requests via API Gateway",
                    "S3 events, DynamoDB streams, API Gateway, SQS messages, CloudWatch Events — and more",
                    "Only scheduled CloudWatch Events",
                    "Only SNS notifications",
                ],
                answer="b",
                explanation="Lambda integrates with most AWS services as an event consumer. S3 object creation, DynamoDB table changes, API calls, SQS messages, scheduled events, Cognito triggers — hundreds of event sources.",
                xp=10,
            ),
            Challenge(
                id="aws_lambda_timeout",
                type="quiz",
                prompt="The maximum execution timeout for a Lambda function is:",
                options=["30 seconds", "5 minutes", "15 minutes", "1 hour"],
                answer="c",
                explanation="Lambda functions have a maximum timeout of 15 minutes (900 seconds). For longer-running workloads, use AWS Fargate, EC2, Step Functions, or break work into smaller functions with SQS between them.",
                xp=10,
            ),
            Challenge(
                id="aws_lambda_cold_start",
                type="fill_blank",
                prompt="The delay experienced when a Lambda function handles its first request after a period of inactivity is called a _____ start.",
                answer="cold",
                explanation="Cold starts occur when AWS must provision a new execution environment. Warm starts reuse existing environments and are much faster. Provisioned Concurrency pre-warms environments to eliminate cold starts for latency-sensitive functions.",
                xp=15,
                hints=["Opposite of 'warm'"],
            ),
            Challenge(
                id="aws_lambda_layers",
                type="quiz",
                prompt="Lambda Layers allow you to:",
                options=[
                    "Run functions across multiple AWS regions simultaneously",
                    "Share code (libraries, dependencies) across multiple Lambda functions without bundling them in each deployment",
                    "Add additional memory beyond the 10 GB limit",
                    "Enable network access from private VPC subnets",
                ],
                answer="b",
                explanation="Layers separate dependencies from function code. A `numpy` layer can be shared across 20 data processing functions — update the layer once, all functions get the update. Also keeps deployment packages small.",
                xp=15,
                hints=["Shared libraries, shared dependencies"],
            ),
            Challenge(
                id="aws_lambda_iam",
                type="quiz",
                prompt="To allow a Lambda function to write to an S3 bucket, you:",
                options=[
                    "Hardcode AWS credentials in the function's environment variables",
                    "Attach an IAM role with S3 write permissions to the Lambda function as its execution role",
                    "Add the Lambda function's ARN to the S3 bucket's ACL",
                    "Enable the Lambda S3 integration in the console",
                ],
                answer="b",
                explanation="Lambda functions use execution roles — IAM roles that define what the function can do. Attach a policy granting `s3:PutObject` to the execution role. No keys needed; credentials are automatically injected.",
                xp=10,
            ),
        ],
    ),
    "cloudwatch_and_monitoring": Zone(
        id="cloudwatch_and_monitoring",
        title="CloudWatch and Monitoring",
        description="Observe AWS infrastructure with metrics, alarms, dashboards, and log analysis.",
        challenges=[
            Challenge(
                id="aws_cw_metrics",
                type="quiz",
                prompt="AWS CloudWatch Metrics are:",
                options=[
                    "Log files from EC2 instances",
                    "Time-series data points published by AWS services — CPU, network, request counts, error rates",
                    "Security audit records of API calls",
                    "Cost and billing reports",
                ],
                answer="b",
                explanation="CloudWatch Metrics are time-series numerical data. AWS services publish them automatically (EC2 CPU, RDS connections, Lambda duration). You can publish custom metrics from your application. Metrics are the foundation for alarms and dashboards.",
                url="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html",
                xp=10,
            ),
            Challenge(
                id="aws_cw_alarms",
                type="quiz",
                prompt="A CloudWatch Alarm transitions to ALARM state when:",
                options=[
                    "Any API error occurs in the account",
                    "A metric breaches a defined threshold for a specified number of evaluation periods",
                    "An EC2 instance is stopped",
                    "A CloudTrail event is recorded",
                ],
                answer="b",
                explanation="Alarms evaluate a metric against a threshold over evaluation periods. Example: CPU > 80% for 3 consecutive 5-minute periods → ALARM. Actions can auto-scale, send SNS notifications, or stop instances. States: OK, ALARM, INSUFFICIENT_DATA.",
                xp=10,
            ),
            Challenge(
                id="aws_cw_logs",
                type="quiz",
                prompt="CloudWatch Logs Insights lets you:",
                options=[
                    "Stream logs to an S3 bucket in real time",
                    "Run SQL queries against CloudWatch log groups to analyze log data",
                    "Archive logs to Glacier automatically",
                    "View EC2 system logs without an agent",
                ],
                answer="b",
                explanation="CloudWatch Logs Insights is a query language for log analysis. Example: `filter @message like /ERROR/ | stats count(*) by bin(5m)` — count errors per 5-minute window. Essential for incident investigation without downloading log files.",
                xp=10,
            ),
            Challenge(
                id="aws_cw_log_retention",
                type="fill_blank",
                prompt="By default, CloudWatch log groups retain logs _____. You must explicitly set a retention policy to control costs.",
                answer="forever",
                explanation="CloudWatch log groups never expire by default — logs accumulate indefinitely and cost increases over time. Always set retention policies (7 days for dev, 90 days for prod, 1 year for compliance). Use S3 lifecycle rules for long-term archival.",
                xp=15,
                hints=["The default is the most expensive option", "No expiry = stores forever"],
            ),
            Challenge(
                id="aws_cw_metric_filter",
                type="quiz",
                prompt="A CloudWatch Metric Filter allows you to:",
                options=[
                    "Block specific log entries from being written",
                    "Extract numerical metrics from log data — e.g., count ERROR occurrences per minute",
                    "Automatically rotate log groups weekly",
                    "Forward logs to a different AWS region",
                ],
                answer="b",
                explanation="Metric Filters parse log data and publish custom metrics. Example: filter log group for 'ERROR' pattern → publish a custom metric `ErrorCount`. Then alarm on that metric. Turns unstructured logs into actionable monitoring signals.",
                xp=10,
            ),
            Challenge(
                id="aws_cw_dashboard",
                type="quiz",
                prompt="CloudWatch Dashboards are useful for:",
                options=[
                    "Automating incident response",
                    "Visualizing metrics from multiple AWS services and accounts on a single screen",
                    "Storing log data in a queryable format",
                    "Setting cost budgets and alerts",
                ],
                answer="b",
                explanation="Dashboards combine widgets (graphs, numbers, alarms) from any metric across services and regions. Build a single pane of glass for your system: RDS connections next to Lambda error rate next to EC2 CPU next to custom application metrics.",
                xp=15,
                hints=["It's a unified view of everything"],
            ),
        ],
    ),
    "cloudformation_and_iac": Zone(
        id="cloudformation_and_iac",
        title="CloudFormation and Infrastructure as Code",
        description="Define, version, and automate AWS infrastructure with CloudFormation templates.",
        challenges=[
            Challenge(
                id="aws_cfn_purpose",
                type="quiz",
                prompt="AWS CloudFormation allows you to:",
                options=[
                    "Monitor AWS resource performance in real time",
                    "Define your entire AWS infrastructure in code (YAML/JSON) and provision it repeatably",
                    "Automatically optimize EC2 instance types",
                    "Manage IAM users from the AWS console",
                ],
                answer="b",
                explanation="CloudFormation is AWS's native Infrastructure as Code service. Define resources in a template; CloudFormation provisions and manages them as a Stack. The same template deploys identical environments in dev, staging, and prod — no manual click-ops.",
                url="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html",
                xp=10,
            ),
            Challenge(
                id="aws_cfn_stack",
                type="quiz",
                prompt="A CloudFormation Stack is:",
                options=[
                    "A collection of EC2 instances running the same AMI",
                    "A collection of AWS resources defined and managed together by a CloudFormation template",
                    "A queue of pending CloudFormation deployments",
                    "A CloudFormation template stored in S3",
                ],
                answer="b",
                explanation="A Stack is a single unit of deployment: all resources from a template are created, updated, and deleted together. If a Stack update fails, CloudFormation automatically rolls back to the previous state — atomic infrastructure changes.",
                xp=10,
            ),
            Challenge(
                id="aws_cfn_change_set",
                type="quiz",
                prompt="Before updating a CloudFormation Stack in production, best practice is to:",
                options=[
                    "Delete and recreate the Stack with the new template",
                    "Update directly — CloudFormation will handle rollback if it fails",
                    "Create a Change Set to preview exactly which resources will be added, modified, or deleted",
                    "Snapshot all EC2 instances in the Stack first",
                ],
                answer="c",
                explanation="Change Sets show the diff between current and new template — which resources will be Added, Modified, Replaced, or Removed. A Replace means the old resource is deleted and recreated (potential downtime/data loss). Always review Change Sets before executing updates.",
                xp=10,
            ),
            Challenge(
                id="aws_cfn_drift",
                type="fill_blank",
                prompt="When someone manually modifies a resource that CloudFormation manages (e.g., via the console), the Stack is said to have _____.",
                answer="drift",
                explanation="Drift occurs when the actual resource state differs from the template. CloudFormation Drift Detection identifies modified resources. Drift breaks the 'infrastructure as code' guarantee — future Stack updates may conflict with manual changes. Prevent drift with IAM policies that block manual resource modification.",
                xp=15,
                hints=["The Stack has drifted from its defined state", "Like a ship drifting off course"],
            ),
            Challenge(
                id="aws_cfn_outputs",
                type="quiz",
                prompt="CloudFormation Stack Outputs are used to:",
                options=[
                    "Print debug logs during Stack creation",
                    "Export values (like a VPC ID or ALB ARN) that other Stacks or scripts can import",
                    "Define the order in which resources are created",
                    "Store Stack creation errors for review",
                ],
                answer="b",
                explanation="Outputs export values from a Stack — VPC ID, database endpoint, certificate ARN. Other Stacks can import them with `Fn::ImportValue`. This enables modular IaC: a network Stack exports VPC/subnet IDs; an application Stack imports them.",
                xp=10,
            ),
            Challenge(
                id="aws_cfn_rollback",
                type="quiz",
                prompt="A CloudFormation Stack update fails partway through. CloudFormation automatically:",
                options=[
                    "Leaves the Stack in a partial state and waits for manual intervention",
                    "Sends an SNS notification but takes no action",
                    "Rolls back all changes — returning all resources to their pre-update state",
                    "Marks the failed resources for deletion and continues",
                ],
                answer="c",
                explanation="CloudFormation treats Stack updates as atomic transactions. On failure, it rolls back every resource that was changed — previous configuration restored. The Stack returns to UPDATE_ROLLBACK_COMPLETE. This prevents partial deployments that are difficult to reason about.",
                xp=15,
                hints=["It's atomic — all or nothing"],
            ),
        ],
    ),
    "ecs_and_containers": Zone(
        id="ecs_and_containers",
        title="ECS and Containers",
        description="Run containerized workloads on AWS with ECS Fargate, task definitions, and ECR.",
        challenges=[
            Challenge(
                id="aws_ecs_vs_eks",
                type="quiz",
                prompt="The main difference between AWS ECS and EKS is:",
                options=[
                    "ECS is cheaper; EKS is faster",
                    "ECS is AWS's proprietary container orchestrator; EKS is managed Kubernetes",
                    "ECS supports Docker; EKS supports only containerd",
                    "ECS is for stateless apps; EKS is for stateful apps",
                ],
                answer="b",
                explanation="ECS (Elastic Container Service) is AWS's own container orchestration platform — simpler, tightly integrated with AWS services. EKS (Elastic Kubernetes Service) is managed Kubernetes — more complex, portable, with the full Kubernetes ecosystem. Choose ECS for AWS-native simplicity; EKS for Kubernetes portability.",
                url="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html",
                xp=10,
            ),
            Challenge(
                id="aws_ecs_fargate",
                type="quiz",
                prompt="AWS Fargate for ECS means:",
                options=[
                    "ECS tasks run on dedicated bare metal servers",
                    "You manage the EC2 instances that run your containers",
                    "AWS manages the underlying infrastructure — you only define task CPU/memory requirements",
                    "Containers run inside Lambda functions",
                ],
                answer="c",
                explanation="Fargate is serverless containers — no EC2 instances to provision, patch, or scale. Define your task (CPU, memory, container image), and Fargate handles placement, scaling, and host management. You pay per task CPU/memory second, not per instance-hour.",
                xp=10,
            ),
            Challenge(
                id="aws_ecs_task_definition",
                type="quiz",
                prompt="An ECS Task Definition is:",
                options=[
                    "A running instance of an ECS task",
                    "A blueprint specifying the container image, CPU, memory, environment variables, and networking for a task",
                    "An IAM policy attached to ECS services",
                    "A load balancer configuration for ECS",
                ],
                answer="b",
                explanation="Task Definitions are versioned blueprints. They specify: container image(s), CPU/memory, port mappings, environment variables, secrets, logging config, and IAM task role. ECS Services use Task Definitions to launch and maintain desired task counts.",
                xp=10,
            ),
            Challenge(
                id="aws_ecr",
                type="fill_blank",
                prompt="The AWS managed Docker container registry — where you push and pull private container images — is called Amazon _____.",
                answer="ECR",
                explanation="ECR (Elastic Container Registry) is a fully managed Docker registry. Images are stored in repositories, scanned for vulnerabilities, replicated across regions, and accessed via IAM policies. ECS tasks use ECR as the image source — no Docker Hub credentials needed.",
                xp=15,
                hints=["Elastic Container Registry — three letters", "Like Docker Hub, but AWS-native"],
            ),
            Challenge(
                id="aws_ecs_task_role",
                type="quiz",
                prompt="An ECS Task Role is different from an ECS Execution Role because:",
                options=[
                    "They are the same — just two names for one IAM role",
                    "Task Role grants permissions to the application code; Execution Role grants ECS permissions to pull images and write logs",
                    "Task Role is for Fargate; Execution Role is for EC2 launch type",
                    "Task Role is optional; Execution Role is required only for Windows containers",
                ],
                answer="b",
                explanation="Two distinct roles: Execution Role = what ECS needs (pull from ECR, write to CloudWatch Logs). Task Role = what your application code needs (read from S3, write to DynamoDB). Separate them — least privilege for both. A compromised container with a minimal Task Role can't access unrelated AWS resources.",
                xp=15,
                hints=["One is for ECS itself; one is for your app"],
            ),
            Challenge(
                id="aws_ecs_service",
                type="quiz",
                prompt="An ECS Service ensures:",
                options=[
                    "A Task runs once and exits successfully",
                    "A specified number of Task replicas are always running, restarting failed tasks and integrating with load balancers",
                    "Tasks are scheduled on a cron schedule",
                    "Container images are kept up to date with the latest ECR push",
                ],
                answer="b",
                explanation="An ECS Service is the long-running equivalent of a Kubernetes Deployment. It maintains desired task count, integrates with ALB for traffic routing, supports rolling deployments, and integrates with Auto Scaling. Use Services for APIs and long-running processes; standalone Tasks for batch jobs.",
                xp=10,
            ),
        ],
    ),
    "elb_and_autoscaling": {
        "id": "elb_and_autoscaling",
        "name": "ELB and Auto Scaling",
        "description": "Load balancers, Auto Scaling Groups, and elastic capacity management.",
        "challenges": [
            {
                "id": "aws_alb_vs_nlb",
                "type": "quiz",
                "prompt": "You're routing HTTP/HTTPS traffic with path-based rules (/api/* to service A, /web/* to service B). Which load balancer type do you use?",
                "options": [
                    "NLB (Network Load Balancer) — operates at Layer 4, TCP/UDP",
                    "ALB (Application Load Balancer) — operates at Layer 7, HTTP/HTTPS with content routing",
                    "CLB (Classic Load Balancer) — legacy, handles both",
                    "GLB (Gateway Load Balancer) — for third-party virtual appliances",
                ],
                "answer": "b",
                "explanation": "ALB operates at Layer 7 and understands HTTP. It supports host-based routing (api.example.com vs web.example.com) and path-based routing (/api/* vs /web/*). NLB operates at Layer 4 (TCP/UDP) — lower latency, static IPs, ideal for non-HTTP protocols.",
                "xp": 10,
                "hints": ["It needs to read URL paths — needs HTTP awareness"],
            },
            {
                "id": "aws_target_group",
                "type": "fill_blank",
                "prompt": "An ALB routes traffic to a _____ Group, which contains the registered targets (EC2 instances, IPs, or Lambda functions).",
                "answer": "Target",
                "explanation": "Target Groups are the backend pools for ALB/NLB. Each target group has a health check configuration. The ALB listener rules forward to specific target groups based on routing conditions.",
                "xp": 10,
                "hints": ["The group that receives the traffic — what are the backends called?"],
            },
            {
                "id": "aws_asg_policy",
                "type": "quiz",
                "prompt": "Your EC2 Auto Scaling Group should add instances when CPU > 70% and remove when CPU < 30%. Which scaling policy type is this?",
                "options": [
                    "Simple Scaling — add/remove a fixed number on a CloudWatch alarm",
                    "Target Tracking Scaling — maintain a target metric value automatically",
                    "Step Scaling — scale by different amounts at different thresholds",
                    "Scheduled Scaling — scale at a specific time of day",
                ],
                "answer": "b",
                "explanation": "Target Tracking is like a thermostat — you say 'keep average CPU at 50%' and AWS adds/removes instances automatically. It's the recommended policy for most use cases. Step Scaling gives more control over exactly how many instances to add at each threshold.",
                "xp": 15,
                "hints": ["You're defining the target value, not the response steps"],
            },
            {
                "id": "aws_asg_cooldown",
                "type": "quiz",
                "prompt": "A Cooldown period in an Auto Scaling Group:",
                "options": [
                    "Prevents instances from being terminated during business hours",
                    "Pauses scaling activity after a scale-out/in event to let metrics stabilize",
                    "Delays the health check on newly launched instances",
                    "Sets the warm-up time before a new instance receives traffic",
                ],
                "answer": "b",
                "explanation": "Cooldown prevents thrashing — after a scaling event, the ASG waits (default 300s) before responding to further alarms. Without it, you might scale out 3 times in quick succession before the first new instance even starts serving traffic.",
                "xp": 10,
                "hints": ["What happens if you keep scaling immediately after each event?"],
            },
            {
                "id": "aws_health_check",
                "type": "quiz",
                "prompt": "An ALB target group health check fails for an instance. The ALB will:",
                "options": [
                    "Terminate the instance immediately and launch a replacement",
                    "Stop routing new requests to that instance until it passes health checks again",
                    "Send an SNS notification to the ops team",
                    "Reroute traffic to the same instance using a different port",
                ],
                "answer": "b",
                "explanation": "ALB marks the instance unhealthy and stops sending new connections to it. In-flight requests complete. If the instance is in an ASG with ELB health checks enabled, the ASG will eventually terminate and replace the unhealthy instance.",
                "xp": 10,
                "hints": ["The instance isn't killed — it's just taken out of rotation"],
            },
            {
                "id": "aws_launch_template",
                "type": "quiz",
                "prompt": "NEXUS evidence: a rogue process is running on every EC2 instance launched by the Auto Scaling Group. The fastest way to stop new instances from running it is to update the _____.",
                "options": [
                    "Security Group inbound rules",
                    "Launch Template — replace the User Data startup script that runs it",
                    "Target Group health check configuration",
                    "CloudWatch alarm threshold",
                ],
                "answer": "b",
                "explanation": "Launch Templates define the blueprint for new EC2 instances: AMI, instance type, key pair, security groups, IAM role, and User Data (startup script). Update the Launch Template with a new version and set the ASG to use it — new instances won't run the rogue process.",
                "xp": 15,
                "hints": ["What controls what runs when an instance first boots?"],
            },
        ],
    },
    "route53_and_cdn": {
        "id": "route53_and_cdn",
        "name": "Route 53 and CloudFront",
        "description": "DNS routing, health checks, failover, and CDN edge caching with CloudFront.",
        "challenges": [
            {
                "id": "aws_route53_alias",
                "type": "quiz",
                "prompt": "You want to point your root domain (example.com) to an ALB. You cannot use a CNAME record for a root domain. The Route 53 solution is to use an _____ record.",
                "options": [
                    "A record pointing to the ALB's static IP",
                    "Alias record — a Route 53 extension that maps the root domain to an AWS resource",
                    "MX record configured with the ALB DNS name",
                    "SOA record override in the hosted zone",
                ],
                "answer": "b",
                "explanation": "CNAME records can't be used for zone apex (root domain) — it's a DNS standard limitation. Route 53 Alias records solve this: they look like A records to the outside world but internally resolve to the DNS name of an AWS resource (ALB, CloudFront, S3, etc.) and update automatically when the resource's IP changes.",
                "xp": 15,
                "hints": ["Route 53 has a special record type that's not standard DNS"],
            },
            {
                "id": "aws_route53_routing",
                "type": "quiz",
                "prompt": "You want to send 10% of traffic to a new version of your app for canary testing. Which Route 53 routing policy do you use?",
                "options": [
                    "Latency-based routing — routes to the lowest-latency region",
                    "Failover routing — active/passive with health checks",
                    "Weighted routing — split traffic by percentage across multiple records",
                    "Geolocation routing — routes by the user's country",
                ],
                "answer": "c",
                "explanation": "Weighted routing lets you assign weights to multiple records for the same name. Weight 90 on v1 and weight 10 on v2 = 10% to v2. Great for blue/green deployments and canary releases.",
                "xp": 10,
                "hints": ["You need to split by percentage"],
            },
            {
                "id": "aws_cloudfront_origin",
                "type": "quiz",
                "prompt": "A CloudFront distribution's Origin is:",
                "options": [
                    "The edge location closest to the user",
                    "The AWS region where CloudFront is deployed",
                    "The backend server (S3, ALB, API Gateway, custom) that CloudFront fetches content from on a cache miss",
                    "The SSL certificate stored in ACM",
                ],
                "answer": "c",
                "explanation": "CloudFront is a CDN — it caches content at edge locations worldwide. On a cache miss, it fetches from the Origin (your S3 bucket, ALB, API Gateway, or any HTTP server). Subsequent requests for the same content are served from the edge cache.",
                "xp": 10,
                "hints": ["Where does CloudFront get the content when it doesn't have it cached?"],
            },
            {
                "id": "aws_cloudfront_ttl",
                "type": "fill_blank",
                "prompt": "To force CloudFront to serve fresh content immediately before the cache TTL expires, you create a cache _____.",
                "answer": "invalidation",
                "explanation": "A CloudFront invalidation removes cached objects from edge locations before they expire. You specify paths like /index.html or /api/* or /* for everything. Invalidations take a few seconds to propagate globally. Note: frequent invalidations beyond the free tier have a cost.",
                "xp": 10,
                "hints": ["The action that removes cached items from edge nodes"],
            },
            {
                "id": "aws_acm",
                "type": "quiz",
                "prompt": "To serve your CloudFront distribution over HTTPS with your custom domain, you need an SSL certificate from _____.",
                "options": [
                    "Route 53 — it issues certificates alongside hosted zones",
                    "ACM (AWS Certificate Manager) in us-east-1 — CloudFront requires the certificate in that specific region",
                    "IAM — SSL certificates can be uploaded to IAM for CloudFront use",
                    "EC2 — certificates are provisioned in the same region as the origin",
                ],
                "answer": "b",
                "explanation": "ACM (AWS Certificate Manager) provides free SSL/TLS certificates. For CloudFront, the certificate MUST be in us-east-1 (N. Virginia) regardless of where your origin is. This is a common gotcha — deploy your ACM cert in the wrong region and CloudFront won't see it.",
                "xp": 15,
                "hints": ["CloudFront is a global service — certificates must be in one specific region"],
            },
            {
                "id": "aws_route53_health",
                "type": "quiz",
                "prompt": "NEXUS delivery server: the primary drop site is down. Route 53 Failover routing will automatically switch to the secondary if you configure a Route 53 _____ on the primary record.",
                "options": [
                    "Geolocation rule pointing to the secondary region",
                    "Health Check — Route 53 monitors the endpoint and triggers failover if it fails",
                    "TTL set to 0 for instant DNS propagation",
                    "Weighted record with weight 0 on failure",
                ],
                "answer": "b",
                "explanation": "Route 53 Health Checks poll an endpoint at regular intervals. When a health check fails, Route 53 stops routing to that record. Combined with Failover routing (PRIMARY/SECONDARY), Route 53 automatically redirects traffic to the secondary when the primary is unhealthy.",
                "xp": 15,
                "hints": ["What does Route 53 need to know the primary is down?"],
            },
        ],
    },
}
