apiVersion: apps/v1
kind: Deployment
metadata:
  name: zenoo-rpc
  namespace: zenoo-production
  labels:
    app: zenoo-rpc
    version: v1.0.0
    component: api
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  selector:
    matchLabels:
      app: zenoo-rpc
  template:
    metadata:
      labels:
        app: zenoo-rpc
        version: v1.0.0
        component: api
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8000"
        prometheus.io/path: "/metrics"
    spec:
      serviceAccountName: zenoo-rpc
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        runAsGroup: 1000
        fsGroup: 1000
      
      initContainers:
      - name: wait-for-redis
        image: redis:7-alpine
        command: ['sh', '-c']
        args:
        - |
          until redis-cli -h redis-service -p 6379 ping; do
            echo "Waiting for Redis..."
            sleep 2
          done
          echo "Redis is ready!"
      
      - name: wait-for-postgres
        image: postgres:15-alpine
        env:
        - name: PGPASSWORD
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: password
        command: ['sh', '-c']
        args:
        - |
          until pg_isready -h postgres-service -p 5432 -U zenoo; do
            echo "Waiting for PostgreSQL..."
            sleep 2
          done
          echo "PostgreSQL is ready!"
      
      containers:
      - name: zenoo-rpc
        image: zenoo-rpc:1.0.0
        imagePullPolicy: IfNotPresent
        
        ports:
        - name: http
          containerPort: 8000
          protocol: TCP
        
        env:
        - name: ENVIRONMENT
          value: "production"
        - name: REDIS_URL
          value: "redis://redis-service:6379/0"
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: url
        - name: LOG_LEVEL
          value: "INFO"
        - name: WORKERS
          value: "4"
        - name: MAX_CONNECTIONS
          value: "20"
        - name: CACHE_BACKEND
          value: "redis"
        - name: ENABLE_METRICS
          value: "true"
        
        resources:
          requests:
            memory: "512Mi"
            cpu: "250m"
            ephemeral-storage: "1Gi"
          limits:
            memory: "1Gi"
            cpu: "1000m"
            ephemeral-storage: "2Gi"
        
        livenessProbe:
          httpGet:
            path: /health
            port: http
            scheme: HTTP
          initialDelaySeconds: 30
          periodSeconds: 10
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 3
        
        readinessProbe:
          httpGet:
            path: /ready
            port: http
            scheme: HTTP
          initialDelaySeconds: 5
          periodSeconds: 5
          timeoutSeconds: 3
          successThreshold: 1
          failureThreshold: 3
        
        startupProbe:
          httpGet:
            path: /health
            port: http
            scheme: HTTP
          initialDelaySeconds: 10
          periodSeconds: 5
          timeoutSeconds: 3
          successThreshold: 1
          failureThreshold: 30
        
        volumeMounts:
        - name: config
          mountPath: /app/config
          readOnly: true
        - name: logs
          mountPath: /app/logs
        - name: tmp
          mountPath: /app/tmp
        
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop:
            - ALL
      
      volumes:
      - name: config
        configMap:
          name: zenoo-rpc-config
      - name: logs
        emptyDir:
          sizeLimit: 1Gi
      - name: tmp
        emptyDir:
          sizeLimit: 500Mi
      
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: app
                  operator: In
                  values:
                  - zenoo-rpc
              topologyKey: kubernetes.io/hostname
      
      tolerations:
      - key: "node.kubernetes.io/not-ready"
        operator: "Exists"
        effect: "NoExecute"
        tolerationSeconds: 300
      - key: "node.kubernetes.io/unreachable"
        operator: "Exists"
        effect: "NoExecute"
        tolerationSeconds: 300

---
apiVersion: v1
kind: Service
metadata:
  name: zenoo-rpc-service
  namespace: zenoo-production
  labels:
    app: zenoo-rpc
    component: api
  annotations:
    prometheus.io/scrape: "true"
    prometheus.io/port: "8000"
    prometheus.io/path: "/metrics"
spec:
  type: ClusterIP
  ports:
  - name: http
    port: 80
    targetPort: http
    protocol: TCP
  selector:
    app: zenoo-rpc

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: zenoo-rpc
  namespace: zenoo-production
  labels:
    app: zenoo-rpc

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: zenoo-rpc-config
  namespace: zenoo-production
  labels:
    app: zenoo-rpc
data:
  production.yaml: |
    # Kubernetes-optimized configuration
    app:
      name: "zenoo-rpc"
      version: "1.0.0"
      environment: "production"
      debug: false
    
    server:
      host: "0.0.0.0"
      port: 8000
      workers: 4
    
    database:
      url: "${DATABASE_URL}"
      pool_size: 20
      max_overflow: 30
    
    cache:
      backend: "redis"
      redis:
        url: "${REDIS_URL}"
        max_connections: 20
        enable_fallback: true
        circuit_breaker_threshold: 5
    
    transaction:
      max_active_transactions: 100
      default_timeout: 300
    
    batch:
      max_chunk_size: 100
      max_concurrency: 10
    
    monitoring:
      metrics:
        enabled: true
        endpoint: "/metrics"
      health:
        enabled: true
        endpoint: "/health"

---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: zenoo-rpc-ingress
  namespace: zenoo-production
  labels:
    app: zenoo-rpc
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-body-size: "10m"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "300"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "300"
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
spec:
  tls:
  - hosts:
    - api.zenoo.example.com
    secretName: zenoo-rpc-tls
  rules:
  - host: api.zenoo.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: zenoo-rpc-service
            port:
              number: 80

---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: zenoo-rpc-pdb
  namespace: zenoo-production
  labels:
    app: zenoo-rpc
spec:
  minAvailable: 2
  selector:
    matchLabels:
      app: zenoo-rpc

---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: zenoo-rpc-hpa
  namespace: zenoo-production
  labels:
    app: zenoo-rpc
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: zenoo-rpc
  minReplicas: 3
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
      - type: Percent
        value: 10
        periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 60
      policies:
      - type: Percent
        value: 50
        periodSeconds: 60
