#!/bin/bash

# Fix "no statefile was found" error
# This script helps resolve Terraform state file issues

set -e

echo "🔧 Fixing 'no statefile was found' error"
echo "======================================"
echo ""
echo "This error occurs when Terraform can't find a state file."
echo "This is normal when importing existing resources for the first time."
echo ""

# Change to terraform directory
cd "$(dirname "$0")/../terraform"

# Function to check current state
check_current_state() {
    echo "🔍 Checking current Terraform state..."
    
    if [ -f "terraform.tfstate" ]; then
        echo "   ✅ Local state file exists"
        echo "   📁 File size: $(du -h terraform.tfstate | cut -f1)"
        echo "   📅 Last modified: $(stat -c %y terraform.tfstate 2>/dev/null || stat -f %Sm terraform.tfstate 2>/dev/null)"
    else
        echo "   ❌ No local state file found"
    fi
    
    if [ -f "terraform.tfstate.backup" ]; then
        echo "   ✅ Backup state file exists"
    else
        echo "   ❌ No backup state file found"
    fi
    
    if [ -d ".terraform" ]; then
        echo "   ✅ .terraform directory exists"
    else
        echo "   ❌ .terraform directory not found"
    fi
    
    echo ""
}

# Function to initialize fresh state
initialize_fresh_state() {
    echo "📦 Initializing fresh Terraform state..."
    
    # Remove existing state files and .terraform directory
    echo "   🗑️  Removing existing state files..."
    rm -f terraform.tfstate*
    rm -rf .terraform/
    
    # Create minimal terraform.tfvars if it doesn't exist
    if [ ! -f "terraform.tfvars" ]; then
        echo "   📝 Creating terraform.tfvars..."
        cat > terraform.tfvars << EOF
aws_region = "us-east-1"
environment = "prod"
allowed_ips = ["0.0.0.0/0"]
db_instance_class = "db.t3.micro"
fargate_cpu = 512
fargate_memory = 1024
min_capacity = 1
max_capacity = 3
enable_s3_force_destroy = false
enable_ecr_force_destroy = false
enable_cloudwatch_cleanup = true
create_final_snapshot = true
EOF
    fi
    
    # Initialize Terraform
    echo "   🚀 Initializing Terraform..."
    terraform init
    
    echo "   ✅ Fresh state initialized!"
    echo ""
}

# Function to create empty state file
create_empty_state() {
    echo "📄 Creating empty state file..."
    
    cat > terraform.tfstate << EOF
{
  "version": 4,
  "terraform_version": "1.5.0",
  "serial": 1,
  "lineage": "$(uuidgen 2>/dev/null || echo $(date +%s))",
  "outputs": {},
  "resources": [],
  "check_results": null
}
EOF
    
    echo "   ✅ Empty state file created!"
    echo ""
}

# Function to import resources step by step
import_resources_step_by_step() {
    echo "📥 Importing resources step by step..."
    echo ""
    
    # Get AWS account ID and region
    ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
    REGION=$(aws configure get region || echo "us-east-1")
    
    echo "📍 AWS Account: $ACCOUNT_ID"
    echo "📍 AWS Region: $REGION"
    echo ""
    
    # VPC Resources
    echo "🌐 Importing VPC resources..."
    VPC_ID=$(aws ec2 describe-vpcs --filters "Name=tag:Project,Values=MalwareWebsiteCrawler" --query "Vpcs[0].VpcId" --output text 2>/dev/null || echo "")
    if [ "$VPC_ID" != "None" ] && [ "$VPC_ID" != "" ]; then
        echo "   Importing VPC: $VPC_ID"
        terraform import aws_vpc.main $VPC_ID || echo "   ⚠️  VPC import failed or already exists"
        
        # Internet Gateway
        IGW_ID=$(aws ec2 describe-internet-gateways --filters "Name=attachment.vpc-id,Values=$VPC_ID" --query "InternetGateways[0].InternetGatewayId" --output text 2>/dev/null || echo "")
        if [ "$IGW_ID" != "None" ] && [ "$IGW_ID" != "" ]; then
            echo "   Importing Internet Gateway: $IGW_ID"
            terraform import aws_internet_gateway.main $IGW_ID || echo "   ⚠️  IGW import failed or already exists"
        fi
        
        # Subnets
        SUBNET_IDS=$(aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPC_ID" --query "Subnets[].SubnetId" --output text)
        if [ ! -z "$SUBNET_IDS" ]; then
            IFS=' ' read -ra SUBNET_ARRAY <<< "$SUBNET_IDS"
            for i in "${!SUBNET_ARRAY[@]}"; do
                if [ "${SUBNET_ARRAY[$i]}" != "None" ] && [ "${SUBNET_ARRAY[$i]}" != "" ]; then
                    echo "   Importing Subnet $((i+1)): ${SUBNET_ARRAY[$i]}"
                    terraform import "aws_subnet.public[$i]" "${SUBNET_ARRAY[$i]}" || echo "   ⚠️  Subnet $((i+1)) import failed or already exists"
                fi
            done
        fi
    fi
    echo ""
    
    # ECS Resources
    echo "🐳 Importing ECS resources..."
    ECS_CLUSTER=$(aws ecs list-clusters --query "clusterArns[?contains(@, 'malware-crawler')]" --output text 2>/dev/null || echo "")
    if [ ! -z "$ECS_CLUSTER" ]; then
        CLUSTER_NAME=$(basename $ECS_CLUSTER)
        echo "   Importing ECS Cluster: $CLUSTER_NAME"
        terraform import aws_ecs_cluster.main $CLUSTER_NAME || echo "   ⚠️  ECS Cluster import failed or already exists"
        
        # ECS Service
        ECS_SERVICE=$(aws ecs list-services --cluster $CLUSTER_NAME --query "serviceArns[?contains(@, 'malware-crawler')]" --output text 2>/dev/null || echo "")
        if [ ! -z "$ECS_SERVICE" ]; then
            SERVICE_NAME=$(basename $ECS_SERVICE)
            echo "   Importing ECS Service: $SERVICE_NAME"
            terraform import aws_ecs_service.main $CLUSTER_NAME/$SERVICE_NAME || echo "   ⚠️  ECS Service import failed or already exists"
        fi
    fi
    echo ""
    
    # RDS Resources
    echo "🗄️  Importing RDS resources..."
    RDS_INSTANCE=$(aws rds describe-db-instances --query "DBInstances[?contains(DBInstanceIdentifier, 'malware-crawler')].DBInstanceIdentifier" --output text 2>/dev/null || echo "")
    if [ "$RDS_INSTANCE" != "None" ] && [ ! -z "$RDS_INSTANCE" ]; then
        echo "   Importing RDS Instance: $RDS_INSTANCE"
        terraform import aws_db_instance.main $RDS_INSTANCE || echo "   ⚠️  RDS Instance import failed or already exists"
    fi
    echo ""
    
    # ElastiCache Resources
    echo "🔴 Importing ElastiCache resources..."
    REDIS_GROUP=$(aws elasticache describe-replication-groups --query "ReplicationGroups[?contains(ReplicationGroupId, 'malware-crawler')].ReplicationGroupId" --output text 2>/dev/null || echo "")
    if [ "$REDIS_GROUP" != "None" ] && [ ! -z "$REDIS_GROUP" ]; then
        echo "   Importing ElastiCache Replication Group: $REDIS_GROUP"
        terraform import aws_elasticache_replication_group.main $REDIS_GROUP || echo "   ⚠️  ElastiCache import failed or already exists"
    fi
    echo ""
    
    # S3 Resources
    echo "💾 Importing S3 resources..."
    S3_BUCKETS=$(aws s3api list-buckets --query "Buckets[?contains(Name, 'malware-crawler')].Name" --output text 2>/dev/null || echo "")
    if [ ! -z "$S3_BUCKETS" ]; then
        IFS=' ' read -ra BUCKET_ARRAY <<< "$S3_BUCKETS"
        for bucket in "${BUCKET_ARRAY[@]}"; do
            if [[ "$bucket" == *"files"* ]]; then
                echo "   Importing S3 Files Bucket: $bucket"
                terraform import aws_s3_bucket.files $bucket || echo "   ⚠️  S3 Files Bucket import failed or already exists"
            elif [[ "$bucket" == *"logs"* ]]; then
                echo "   Importing S3 Logs Bucket: $bucket"
                terraform import aws_s3_bucket.logs $bucket || echo "   ⚠️  S3 Logs Bucket import failed or already exists"
            fi
        done
    fi
    echo ""
    
    # Load Balancer Resources
    echo "⚖️  Importing Load Balancer resources..."
    ALB_ARN=$(aws elbv2 describe-load-balancers --query "LoadBalancers[?contains(LoadBalancerName, 'malware-crawler')].LoadBalancerArn" --output text 2>/dev/null || echo "")
    if [ "$ALB_ARN" != "None" ] && [ ! -z "$ALB_ARN" ]; then
        echo "   Importing Application Load Balancer: $ALB_ARN"
        terraform import aws_lb.main $ALB_ARN || echo "   ⚠️  ALB import failed or already exists"
        
        # Target Group
        TG_ARN=$(aws elbv2 describe-target-groups --query "TargetGroups[?contains(TargetGroupName, 'malware-crawler')].TargetGroupArn" --output text 2>/dev/null || echo "")
        if [ "$TG_ARN" != "None" ] && [ ! -z "$TG_ARN" ]; then
            echo "   Importing Target Group: $TG_ARN"
            terraform import aws_lb_target_group.app $TG_ARN || echo "   ⚠️  Target Group import failed or already exists"
        fi
    fi
    echo ""
    
    # Security Groups
    echo "🔒 Importing Security Groups..."
    SG_IDS=$(aws ec2 describe-security-groups --filters "Name=group-name,Values=*malware-crawler*" --query "SecurityGroups[].GroupId" --output text 2>/dev/null || echo "")
    if [ ! -z "$SG_IDS" ]; then
        IFS=' ' read -ra SG_ARRAY <<< "$SG_IDS"
        for sg_id in "${SG_ARRAY[@]}"; do
            if [ "$sg_id" != "None" ] && [ "$sg_id" != "" ]; then
                SG_NAME=$(aws ec2 describe-security-groups --group-ids $sg_id --query "SecurityGroups[0].GroupName" --output text 2>/dev/null || echo "")
                echo "   Importing Security Group: $SG_NAME ($sg_id)"
                case "$SG_NAME" in
                    *"alb"*)
                        terraform import aws_security_group.alb $sg_id || echo "   ⚠️  ALB Security Group import failed"
                        ;;
                    *"ecs"*)
                        terraform import aws_security_group.ecs_tasks $sg_id || echo "   ⚠️  ECS Security Group import failed"
                        ;;
                    *"rds"*)
                        terraform import aws_security_group.rds $sg_id || echo "   ⚠️  RDS Security Group import failed"
                        ;;
                    *"redis"*)
                        terraform import aws_security_group.redis $sg_id || echo "   ⚠️  Redis Security Group import failed"
                        ;;
                esac
            fi
        done
    fi
    echo ""
    
    echo "✅ Import process completed!"
    echo ""
}

# Function to verify state
verify_state() {
    echo "🔍 Verifying Terraform state..."
    echo ""
    
    # Show current state
    echo "📊 Current Terraform state:"
    terraform state list
    
    echo ""
    echo "📋 State summary:"
    terraform show -json | jq -r '.values.root_module.resources[] | "\(.type).\(.name): \(.values.id // "N/A")"' 2>/dev/null || terraform show
    
    echo ""
    echo "💡 Next steps:"
    echo "   1. Review the state list above"
    echo "   2. Run 'terraform plan' to see what changes Terraform wants to make"
    echo "   3. If everything looks good, you can now use 'terraform destroy'"
    echo ""
}

# Main execution
echo "🚀 Starting state file fix process..."
echo ""

# Check AWS CLI
if ! command -v aws &> /dev/null; then
    echo "❌ AWS CLI not found. Please install and configure AWS CLI first."
    exit 1
fi

# Check if AWS credentials are configured
if ! aws sts get-caller-identity &> /dev/null; then
    echo "❌ AWS credentials not configured. Please run 'aws configure' first."
    exit 1
fi

# Check current state
check_current_state

# Ask user what they want to do
echo "🎯 What would you like to do?"
echo "1. Initialize fresh state and import resources"
echo "2. Create empty state file and import resources"
echo "3. Just verify current state"
echo "4. Exit"
echo ""

read -p "Enter your choice (1-4): " choice

case $choice in
    1)
        echo "🔄 Initializing fresh state and importing resources..."
        initialize_fresh_state
        import_resources_step_by_step
        verify_state
        ;;
    2)
        echo "🔄 Creating empty state file and importing resources..."
        create_empty_state
        import_resources_step_by_step
        verify_state
        ;;
    3)
        echo "🔍 Verifying current state..."
        verify_state
        ;;
    4)
        echo "👋 Exiting..."
        exit 0
        ;;
    *)
        echo "❌ Invalid choice. Please run the script again."
        exit 1
        ;;
esac

echo "🎉 State file fix completed successfully!"
echo ""
echo "📝 Important notes:"
echo "   - Some resources may need manual configuration in terraform files"
echo "   - Run 'terraform plan' to see what changes are needed"
echo "   - You can now use 'terraform destroy' to remove all resources"
echo ""
echo "🔧 If you encounter issues:"
echo "   - Check terraform.tfvars configuration"
echo "   - Verify resource names match your actual AWS resources"
echo "   - Some resources may need to be imported manually"
