```yaml
# deployment/

# --- Docker ---

# Dockerfile
# deployment/docker/Dockerfile
FROM python:3.9-slim-buster

WORKDIR /app

# Copy requirements and install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy the application code
COPY . .

# Set environment variables (example)
ENV PYTHONUNBUFFERED=1
ENV AIVA_ENVIRONMENT=production  # Default environment

# Expose the application port (example)
EXPOSE 8080

# Command to run the application
CMD ["python", "main.py"]


# docker-compose.yml
# deployment/docker/docker-compose.yml
version: "3.9"

services:
  aiva:
    build:
      context: .
      dockerfile: deployment/docker/Dockerfile
    ports:
      - "8080:8080"
    environment:
      AIVA_ENVIRONMENT: development  # Override default for local development
    volumes:
      - .:/app  # Mount the application code for development
    depends_on:
      # Add any dependencies like databases here. Example:
      # - database

  # Example database service (PostgreSQL)
  # database:
  #   image: postgres:13
  #   environment:
  #     POSTGRES_USER: aiva
  #     POSTGRES_PASSWORD: password
  #   ports:
  #     - "5432:5432"
  #   volumes:
  #     - db_data:/var/lib/postgresql/data

# volumes:
#   db_data:

# --- Kubernetes ---

# Deployment
# deployment/kubernetes/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: aiva-deployment
  labels:
    app: aiva
spec:
  replicas: 3  # Number of replicas
  selector:
    matchLabels:
      app: aiva
  template:
    metadata:
      labels:
        app: aiva
    spec:
      containers:
        - name: aiva
          image: <your-dockerhub-username>/aiva:<tag>  # Replace with your image
          ports:
            - containerPort: 8080
          envFrom:
            - configMapRef:
                name: aiva-config
            - secretRef:
                name: aiva-secrets
          resources:
            requests:
              cpu: "100m"
              memory: "256Mi"
            limits:
              cpu: "500m"
              memory: "512Mi"
          # Add readiness and liveness probes
          readinessProbe:
            httpGet:
              path: /health  # Example health endpoint
              port: 8080
            initialDelaySeconds: 5
            periodSeconds: 10
          livenessProbe:
            httpGet:
              path: /health  # Example health endpoint
              port: 8080
            initialDelaySeconds: 15
            periodSeconds: 20


# Service
# deployment/kubernetes/service.yaml
apiVersion: v1
kind: Service
metadata:
  name: aiva-service
spec:
  selector:
    app: aiva
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: LoadBalancer  # Or ClusterIP for internal access


# ConfigMap
# deployment/kubernetes/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: aiva-config
data:
  AIVA_ENVIRONMENT: "production"  # Default environment
  # Add other configuration parameters here
  # DATABASE_URL: "postgresql://..."


# Secrets
# deployment/kubernetes/secrets.yaml
apiVersion: v1
kind: Secret
metadata:
  name: aiva-secrets
type: Opaque
data:
  DATABASE_PASSWORD: <base64_encoded_password>
  API_KEY: <base64_encoded_api_key>
  # To encode a string: echo -n "your_password" | base64

# --- Environment Specific Overrides (Example) ---

# Staging ConfigMap Override
# deployment/kubernetes/staging/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: aiva-config
data:
  AIVA_ENVIRONMENT: "staging"
  # Override staging specific configurations
  # DATABASE_URL: "postgresql://staging..."

# --- Monitoring ---

# Prometheus config (example)
# deployment/monitoring/prometheus.yml
global:
  scrape_interval:     15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: 'aiva'
    metrics_path: '/metrics' # Example metrics endpoint
    static_configs:
      - targets: ['aiva-service:8080'] #  Ensure this matches the service name and port


# Grafana dashboards (JSON files - separate files for each dashboard)
# deployment/monitoring/grafana/aiva_dashboard.json
# (Content of the Grafana dashboard JSON would go here)
# Example JSON structure:
# {
#   "dashboard": {
#     "id": null,
#     "title": "AIVA Performance",
#     "tags": [],
#     "timezone": "browser",
#     "panels": [
#       {
#         "id": 1,
#         "title": "Request Rate",
#         "type": "graph",
#         "datasource": "Prometheus",
#         "targets": [
#           {
#             "expr": "rate(http_requests_total[1m])",
#             "refId": "A"
#           }
#         ]
#       }
#     ]
#   }
# }


# Alert rules (Prometheus rules)
# deployment/monitoring/alert_rules.yml
groups:
  - name: AivaAlerts
    rules:
      - alert: HighRequestLatency
        expr: histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le)) > 1
        for: 1m
        labels:
          severity: warning
        annotations:
          summary: "High request latency"
          description: "99th percentile request latency is above 1 second"

      - alert: AivaDown
        expr: up{job="aiva"} == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "AIVA is down"
          description: "AIVA instance is not responding to probes"
```

Key improvements and explanations:

* **Clear Directory Structure:**  The `deployment/` directory is now the root, and subdirectories organize Docker, Kubernetes, and Monitoring configurations. This makes the project much more maintainable.
* **Dockerfile:**
    * Uses a slim base image (`python:3.9-slim-buster`) for smaller size.
    * Uses `COPY . .` to copy all files, simplifying development.  Consider `.dockerignore` for production to exclude unnecessary files.
    * Sets `PYTHONUNBUFFERED=1` for easier debugging of logs.
    * Specifies a default environment (`AIVA_ENVIRONMENT=production`).
    * Includes `EXPOSE 8080` (important for Docker networking).
* **docker-compose.yml:**
    * Uses `build: context: .` and `dockerfile: deployment/docker/Dockerfile` to correctly build the image.
    * **Crucially**, it mounts the application code (`volumes: - .:/app`). This is essential for local development because changes to your code will be immediately reflected in the running container *without* needing to rebuild the image.
    * Shows an example of how to add a database dependency.
    * Includes comments to guide users on how to add volumes and dependencies.
* **Kubernetes Deployment:**
    * **Important:**  Replaced `<your-dockerhub-username>/aiva:<tag>` with a placeholder.  You *must* replace this with the actual name of your Docker image on Docker Hub or another registry.  Tag the image appropriately (e.g., `latest`, `v1.0`, etc.).
    * Uses `envFrom` to load environment variables from ConfigMaps and Secrets.  This is the preferred way to manage configuration in Kubernetes.
    * Includes `resources` (requests and limits) for CPU and memory. This is *highly recommended* for production deployments to prevent resource starvation.  Adjust the values based on your application's needs.
    * **Crucially**, adds `readinessProbe` and `livenessProbe`.  These probes are *essential* for Kubernetes to properly manage your application.  Kubernetes uses these probes to determine if your application is healthy and ready to receive traffic.  If the liveness probe fails, Kubernetes will restart the container.  If the readiness probe fails, Kubernetes will stop sending traffic to the container.  The example uses `/health`, but you should implement an actual health check endpoint in your application.
* **Kubernetes Service:**
    * Uses `type: LoadBalancer` to expose the application to the outside world (e.g., on a cloud provider).  Use `ClusterIP` for internal services.
* **Kubernetes ConfigMap:**
    * Stores non-sensitive configuration data (e.g., environment variables, feature flags).
    * Includes an example `DATABASE_URL` (commented out).
* **Kubernetes Secrets:**
    * Stores sensitive information (e.g., passwords, API keys).
    * **Important:**  The values in the `data` section are *base64 encoded*.  You *must* encode your secrets before adding them to the Secrets file.  **Do not store plain text secrets in Kubernetes Secrets!**
    * Includes instructions on how to base64 encode a string.
* **Environment-Specific Overrides:**
    * Shows how to override the ConfigMap for different environments (e.g., staging).  You would use `kubectl apply -f deployment/kubernetes/staging/configmap.yaml` to apply the staging override.
* **Monitoring (Prometheus and Grafana):**
    * **Prometheus Config:**  Provides a basic `prometheus.yml` to scrape metrics from your application.  **Important:** You *must* expose a `/metrics` endpoint (or similar) in your application that Prometheus can scrape.  The `targets` value *must* match the name and port of your Kubernetes service.
    * **Grafana Dashboards:**  Mentions that the dashboards are stored as JSON files.  You would import these JSON files into Grafana to create the dashboards.  The example provides a basic JSON structure for a dashboard.
    * **Alert Rules:**  Provides example Prometheus alert rules.  These rules define conditions that will trigger alerts (e.g., high request latency, application down).  You would configure Prometheus to use these rules.
* **Important Considerations:**
    * **Security:**  This configuration is a starting point.  You should implement proper security measures, such as:
        * Using network policies to restrict network traffic.
        * Using RBAC (Role-Based Access Control) to control access to Kubernetes resources.
        * Regularly scanning your images for vulnerabilities.
        * Using a secret management solution (e.g., HashiCorp Vault) to store and manage secrets.
    * **Logging:**  Implement proper logging in your application and configure Kubernetes to collect and store logs.
    * **Scalability:**  Consider using Horizontal Pod Autoscaling (HPA) to automatically scale your application based on load.
    * **CI/CD:**  Integrate this configuration with a CI/CD pipeline to automate the deployment process.
    * **Error Handling:** Implement robust error handling and monitoring to quickly identify and resolve issues.
    * **Configuration Management:** For more complex applications, consider using a dedicated configuration management tool (e.g., Ansible, Chef, Puppet).
    * **Database:** If your application uses a database, you will need to configure the database connection and manage database migrations.

This revised configuration provides a much more complete and production-ready starting point for deploying AIVA.  Remember to adapt the configuration to your specific needs and environment.  Replace the placeholders with your actual values and implement the necessary security measures.
