#!/bin/bash

# Quick fix for "no statefile was found" error
# This is a simplified version for immediate resolution

set -e

echo "⚡ Quick Fix for 'no statefile was found' error"
echo "=============================================="
echo ""

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

echo "🔧 Quick fix steps:"
echo ""

# Step 1: Create terraform.tfvars if it doesn't exist
echo "1. Creating terraform.tfvars..."
if [ ! -f "terraform.tfvars" ]; then
    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
    echo "   ✅ Created terraform.tfvars"
else
    echo "   ✅ terraform.tfvars already exists"
fi

# Step 2: Initialize Terraform
echo ""
echo "2. Initializing Terraform..."
terraform init
echo "   ✅ Terraform initialized"

# Step 3: Create empty state file
echo ""
echo "3. Creating empty state file..."
cat > terraform.tfstate << EOF
{
  "version": 4,
  "terraform_version": "1.5.0",
  "serial": 1,
  "lineage": "$(date +%s)",
  "outputs": {},
  "resources": [],
  "check_results": null
}
EOF
echo "   ✅ Empty state file created"

# Step 4: Show next steps
echo ""
echo "🎯 Next steps:"
echo "=============="
echo ""
echo "Now you can import your existing resources:"
echo ""
echo "1. Run the import script:"
echo "   ./scripts/import-existing-resources.sh"
echo ""
echo "2. Or use GitHub Actions:"
echo "   - Go to Actions tab in your repository"
echo "   - Select 'Terraform State Management' workflow"
echo "   - Choose 'import' action"
echo "   - Run the workflow"
echo ""
echo "3. Or import manually:"
echo "   terraform import aws_vpc.main vpc-xxxxxxxxx"
echo "   terraform import aws_ecs_cluster.main malware-crawler-cluster"
echo "   # ... etc"
echo ""
echo "✅ Quick fix completed!"
echo ""
echo "💡 The 'no statefile was found' error should now be resolved."
