"""
Template Generator

This module handles generating project templates and examples for different
cloud providers and environments.
"""

import shutil
from pathlib import Path
from typing import Dict


def get_template_content(template_name: str, provider: str, environment: str) -> Dict[str, str]:
    """Get template content for different providers and environments"""
    
    # Base templates for different providers
    templates = {
        "aws": {
            "main.py": f'''"""
{environment.title()} Environment - AWS Infrastructure
Generated by InfraDSL init command
"""

# AWS Infrastructure for {environment} environment
from infradsl import AWS

# Web Application Stack
web_server = (AWS.EC2("web-server")
    .t3_micro()
    .ubuntu()
    .service("nginx")
    .public_ip()
    .create())

# Database
database = (AWS.RDS("app-db")
    .postgresql()
    .db_t3_micro()
    .storage(20)
    .create())

# Storage for static assets
storage = (AWS.S3("app-assets")
    .website()
    .public()
    .lifecycle(30)
    .create())

print(f"✅ {environment.title()} environment infrastructure created!")
print(f"🌐 Web server: {{web_server['ip_address']}}")
print(f"🗄️  Database: {{database['endpoint']}}")
print(f"📦 Storage: {{storage['bucket_name']}}")
''',
            ".env": f'''# AWS Configuration for {environment} environment
AWS_ACCESS_KEY_ID=your_access_key_here
AWS_SECRET_ACCESS_KEY=your_secret_key_here
AWS_DEFAULT_REGION=us-east-1

# Environment
ENVIRONMENT={environment}
''',
            "README.md": f'''# {environment.title()} Environment - AWS

This infrastructure was generated using InfraDSL.

## Quick Start

1. **Configure AWS credentials:**
   ```bash
   cp .env.example .env
   # Edit .env with your AWS credentials
   ```

2. **Preview the infrastructure:**
   ```bash
   infradsl preview main.py
   ```

3. **Deploy the infrastructure:**
   ```bash
   infradsl apply main.py
   ```

4. **Destroy when done:**
   ```bash
   infradsl destroy main.py
   ```

## Resources Created

- **EC2 Instance**: Web server with nginx
- **RDS Database**: PostgreSQL database
- **S3 Bucket**: Static asset storage

## Next Steps

- Customize the infrastructure in `main.py`
- Add more services as needed
- Set up monitoring and logging
'''
        },
        
        "gcp": {
            "main.py": f'''"""
{environment.title()} Environment - Google Cloud Infrastructure
Generated by InfraDSL init command
"""

# Google Cloud Infrastructure for {environment} environment
from infradsl import GoogleCloud

# Compute Engine VM
web_server = (GoogleCloud.VM("web-server")
    .e2_micro()
    .ubuntu()
    .service("nginx")
    .public_ip()
    .create())

# Cloud SQL Database
database = (GoogleCloud.CloudSQL("app-db")
    .postgresql()
    .db_f1_micro()
    .storage(10)
    .create())

# Cloud Storage
storage = (GoogleCloud.Storage("app-assets")
    .bucket()
    .public()
    .lifecycle(30)
    .create())

print(f"✅ {environment.title()} environment infrastructure created!")
print(f"🌐 Web server: {{web_server['ip_address']}}")
print(f"🗄️  Database: {{database['connection_name']}}")
print(f"📦 Storage: {{storage['bucket_name']}}")
''',
            ".env": f'''# Google Cloud Configuration for {environment} environment
GOOGLE_APPLICATION_CREDENTIALS=path/to/your/service-account.json
GOOGLE_CLOUD_PROJECT=your-project-id

# Environment
ENVIRONMENT={environment}
''',
            "README.md": f'''# {environment.title()} Environment - Google Cloud

This infrastructure was generated using InfraDSL.

## Quick Start

1. **Configure Google Cloud credentials:**
   ```bash
   cp .env.example .env
   # Edit .env with your GCP project and credentials
   ```

2. **Preview the infrastructure:**
   ```bash
   infradsl preview main.py
   ```

3. **Deploy the infrastructure:**
   ```bash
   infradsl apply main.py
   ```

4. **Destroy when done:**
   ```bash
   infradsl destroy main.py
   ```

## Resources Created

- **Compute Engine VM**: Web server with nginx
- **Cloud SQL**: PostgreSQL database
- **Cloud Storage**: Static asset storage

## Next Steps

- Customize the infrastructure in `main.py`
- Add more services as needed
- Set up monitoring and logging
'''
        },
        
        "digitalocean": {
            "main.py": f'''"""
{environment.title()} Environment - DigitalOcean Infrastructure
Generated by InfraDSL init command
"""

# DigitalOcean Infrastructure for {environment} environment
from infradsl import DigitalOcean

# Droplet (VM)
web_server = (DigitalOcean.Droplet("web-server")
    .basic()
    .ubuntu()
    .service("nginx")
    .public_ip()
    .create())

# Load Balancer
load_balancer = (DigitalOcean.LoadBalancer("app-lb")
    .http(80)
    .health_check("/")
    .add_droplet(web_server)
    .create())

# Container Registry
registry = (DigitalOcean.ContainerRegistry("app-registry")
    .basic()
    .create())

print(f"✅ {environment.title()} environment infrastructure created!")
print(f"🌐 Web server: {{web_server['ip_address']}}")
print(f"⚖️  Load balancer: {{load_balancer['ip_address']}}")
print(f"📦 Registry: {{registry['registry_name']}}")
''',
            ".env": f'''# DigitalOcean Configuration for {environment} environment
DIGITALOCEAN_TOKEN=your_api_token_here
DIGITALOCEAN_REGION=nyc1

# Environment
ENVIRONMENT={environment}
''',
            "README.md": f'''# {environment.title()} Environment - DigitalOcean

This infrastructure was generated using InfraDSL.

## Quick Start

1. **Configure DigitalOcean credentials:**
   ```bash
   cp .env.example .env
   # Edit .env with your DigitalOcean API token
   ```

2. **Preview the infrastructure:**
   ```bash
   infradsl preview main.py
   ```

3. **Deploy the infrastructure:**
   ```bash
   infradsl apply main.py
   ```

4. **Destroy when done:**
   ```bash
   infradsl destroy main.py
   ```

## Resources Created

- **Droplet**: Web server with nginx
- **Load Balancer**: Traffic distribution
- **Container Registry**: Docker image storage

## Next Steps

- Customize the infrastructure in `main.py`
- Add more services as needed
- Set up monitoring and logging
'''
        }
    }
    
    return templates.get(provider, {})


def create_project_structure(project_path: str, provider: str, environment: str):
    """Create the complete project structure with templates"""
    
    # Create project directory
    project_dir = Path(project_path)
    project_dir.mkdir(parents=True, exist_ok=True)
    
    # Get template content
    templates = get_template_content("main", provider, environment)
    
    # Create main infrastructure file
    main_file = project_dir / "main.py"
    with open(main_file, 'w') as f:
        f.write(templates.get("main.py", ""))
    
    # Create environment file
    env_file = project_dir / ".env"
    with open(env_file, 'w') as f:
        f.write(templates.get(".env", ""))
    
    # Create README
    readme_file = project_dir / "README.md"
    with open(readme_file, 'w') as f:
        f.write(templates.get("README.md", ""))
    
    # Create examples directory
    examples_dir = project_dir / "examples"
    examples_dir.mkdir(exist_ok=True)
    
    # Create provider-specific examples
    if provider == "aws":
        create_aws_examples(examples_dir, environment)
    elif provider == "gcp":
        create_gcp_examples(examples_dir, environment)
    elif provider == "digitalocean":
        create_do_examples(examples_dir, environment)
    
    # Create templates directory
    templates_dir = project_dir / "templates"
    templates_dir.mkdir(exist_ok=True)
    
    # Create .gitignore
    gitignore_file = project_dir / ".gitignore"
    with open(gitignore_file, 'w') as f:
        f.write(_get_gitignore_content())


def create_aws_examples(examples_dir: Path, environment: str):
    """Create AWS-specific examples"""
    
    # Simple web app example
    webapp_example = examples_dir / "webapp.py"
    with open(webapp_example, 'w') as f:
        f.write(f'''"""
AWS Web Application Example
A complete web application with load balancer, auto-scaling, and database
"""

from infradsl import AWS

# VPC and Networking
vpc = (AWS.VPC("webapp-vpc")
    .cidr("10.0.0.0/16")
    .enable_dns()
    .create())

# Application Load Balancer
load_balancer = (AWS.LoadBalancer("webapp-lb")
    .application()
    .internet_facing()
    .vpc(vpc)
    .health_check("/health")
    .create())

# Auto Scaling Group
auto_scaling = (AWS.AutoScaling("webapp-asg")
    .min_size(2)
    .max_size(10)
    .desired_capacity(3)
    .instance_type("t3.micro")
    .vpc(vpc)
    .load_balancer(load_balancer)
    .create())

# RDS Database
database = (AWS.RDS("webapp-db")
    .postgresql()
    .db_t3_micro()
    .storage(20)
    .vpc(vpc)
    .backup_retention(7)
    .create())

print("✅ Web application infrastructure created!")
print(f"🌐 Load balancer: {{load_balancer['dns_name']}}")
print(f"🗄️  Database: {{database['endpoint']}}")
''')
    
    # Serverless example
    serverless_example = examples_dir / "serverless.py"
    with open(serverless_example, 'w') as f:
        f.write(f'''"""
AWS Serverless Example
A serverless application with Lambda, API Gateway, and DynamoDB
"""

from infradsl import AWS

# DynamoDB Table
dynamodb = (AWS.DynamoDB("user-data")
    .primary_key("user_id", "S")
    .billing_mode("PAY_PER_REQUEST")
    .create())

# Lambda Function
lambda_function = (AWS.Lambda("api-handler")
    .python39()
    .code_from_directory("./src")
    .handler("app.handler")
    .environment({{"TABLE_NAME": dynamodb['table_name']}})
    .create())

# API Gateway
api_gateway = (AWS.APIGateway("user-api")
    .lambda_integration(lambda_function)
    .cors_enabled()
    .api_key_required()
    .create())

print("✅ Serverless application infrastructure created!")
print(f"🚪 API Endpoint: {{api_gateway['api_url']}}")
print(f"⚡ Lambda Function: {{lambda_function['function_name']}}")
print(f"🗄️  DynamoDB Table: {{dynamodb['table_name']}}")
''')
    
    # Container example
    container_example = examples_dir / "containers.py"
    with open(container_example, 'w') as f:
        f.write(f'''"""
AWS Container Example
ECS Fargate service with ECR registry
"""

from infradsl import AWS

# ECR Repository
ecr_repo = (AWS.ECR("webapp-repo")
    .lifecycle_policy(max_images=10)
    .scan_on_push()
    .create())

# ECS Cluster
ecs_cluster = (AWS.ECS("webapp-cluster")
    .fargate()
    .create())

# ECS Service
ecs_service = (AWS.ECSService("webapp-service")
    .cluster(ecs_cluster)
    .container_image(ecr_repo)
    .cpu(256)
    .memory(512)
    .desired_count(2)
    .public()
    .create())

print("✅ Container infrastructure created!")
print(f"🐳 ECR Repository: {{ecr_repo['repository_uri']}}")
print(f"🚀 ECS Service: {{ecs_service['service_name']}}")
''')


def create_gcp_examples(examples_dir: Path, environment: str):
    """Create Google Cloud-specific examples"""
    
    # Web app example
    webapp_example = examples_dir / "webapp.py"
    with open(webapp_example, 'w') as f:
        f.write(f'''"""
Google Cloud Web Application Example
A complete web application with load balancer and database
"""

from infradsl import GoogleCloud

# Compute Engine Instance Template
instance_template = (GoogleCloud.InstanceTemplate("webapp-template")
    .machine_type("e2-micro")
    .ubuntu()
    .startup_script("./startup.sh")
    .create())

# Managed Instance Group
instance_group = (GoogleCloud.ManagedInstanceGroup("webapp-group")
    .template(instance_template)
    .target_size(3)
    .auto_scaling(min_replicas=2, max_replicas=10)
    .create())

# Load Balancer
load_balancer = (GoogleCloud.LoadBalancer("webapp-lb")
    .http()
    .backend_service(instance_group)
    .health_check("/health")
    .create())

# Cloud SQL Database
database = (GoogleCloud.CloudSQL("webapp-db")
    .postgresql()
    .tier("db-f1-micro")
    .storage(10)
    .backup_enabled()
    .create())

print("✅ Web application infrastructure created!")
print(f"🌐 Load balancer IP: {{load_balancer['ip_address']}}")
print(f"🗄️  Database: {{database['connection_name']}}")
''')
    
    # Serverless example  
    serverless_example = examples_dir / "serverless.py"
    with open(serverless_example, 'w') as f:
        f.write(f'''"""
Google Cloud Serverless Example
Cloud Functions with Firestore and Cloud Storage
"""

from infradsl import GoogleCloud

# Firestore Database
firestore = (GoogleCloud.Firestore("app-data")
    .native_mode()
    .create())

# Cloud Storage Bucket
storage = (GoogleCloud.Storage("app-uploads")
    .standard_storage()
    .public_read()
    .lifecycle_rule(delete_after_days=90)
    .create())

# Cloud Function
cloud_function = (GoogleCloud.CloudFunction("api-handler")
    .python39()
    .source_directory("./src")
    .entry_point("main")
    .trigger_http()
    .environment({{"FIRESTORE_PROJECT": firestore['project_id']}})
    .create())

print("✅ Serverless application infrastructure created!")
print(f"🚪 Function URL: {{cloud_function['trigger_url']}}")
print(f"🗄️  Firestore: {{firestore['database_id']}}")
print(f"📦 Storage: {{storage['bucket_name']}}")
''')


def create_do_examples(examples_dir: Path, environment: str):
    """Create DigitalOcean-specific examples"""
    
    # Web app example
    webapp_example = examples_dir / "webapp.py"
    with open(webapp_example, 'w') as f:
        f.write(f'''"""
DigitalOcean Web Application Example
Multiple droplets with load balancer and database
"""

from infradsl import DigitalOcean

# Database
database = (DigitalOcean.Database("webapp-db")
    .postgresql()
    .basic()
    .nodes(1)
    .create())

# Web Server Droplets
web_droplets = []
for i in range(3):
    droplet = (DigitalOcean.Droplet(f"web-{i+1}")
        .basic()
        .ubuntu()
        .startup_script("./web-setup.sh")
        .vpc_network()
        .create())
    web_droplets.append(droplet)

# Load Balancer
load_balancer = (DigitalOcean.LoadBalancer("webapp-lb")
    .http(80)
    .https(443)
    .health_check("/health")
    .add_droplets(web_droplets)
    .create())

print("✅ Web application infrastructure created!")
print(f"🌐 Load balancer IP: {{load_balancer['ip_address']}}")
print(f"🗄️  Database: {{database['connection_string']}}")
''')
    
    # Container example
    container_example = examples_dir / "containers.py"
    with open(container_example, 'w') as f:
        f.write(f'''"""
DigitalOcean Container Example
App Platform with container registry
"""

from infradsl import DigitalOcean

# Container Registry
registry = (DigitalOcean.ContainerRegistry("webapp-registry")
    .basic()
    .create())

# App Platform
app_platform = (DigitalOcean.AppPlatform("webapp-app")
    .docker_image(registry, "webapp:latest")
    .basic_plan()
    .instance_count(2)
    .environment_variables({
        "NODE_ENV": "production",
        "PORT": "3000"
    })
    .create())

print("✅ Container application infrastructure created!")
print(f"📦 Registry: {{registry['registry_name']}}")
print(f"🚀 App URL: {{app_platform['live_url']}}")
''')


def _get_gitignore_content() -> str:
    """Get the content for .gitignore file"""
    return '''# Environment variables
.env
.env.local
.env.*.local

# InfraDSL state files
*.state
.infradsl/

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
ENV/
env.bak/
venv.bak/

# IDEs
.vscode/
.idea/
*.swp
*.swo
*~

# OS files
.DS_Store
Thumbs.db

# Logs
*.log
logs/

# Temporary files
*.tmp
*.temp
.cache/

# Credentials (never commit these!)
*credentials*.json
*service-account*.json
*.pem
*.key
'''