---
# Deploy Veza V5 Ultra applications in containers (simplified version)
# Builds and runs backend, chat, stream, and web services

- name: Deploy Veza V5 Ultra applications
  hosts: edge
  become: true
  gather_facts: true

  vars:
    domain: "{{ domain | default('veza.talas.fr') }}"
    backend_container: "veza-backend"
    chat_container: "veza-chat"
    stream_container: "veza-stream"
    web_container: "veza-web"

  tasks:
    - name: Deploy Go Backend API
      block:
        - name: Install Go in backend container
          command: |
            incus exec {{ backend_container }} -- apt update
            incus exec {{ backend_container }} -- apt install -y wget git
            incus exec {{ backend_container }} -- wget https://go.dev/dl/go1.21.5.linux-amd64.tar.gz
            incus exec {{ backend_container }} -- tar -C /usr/local -xzf go1.21.5.linux-amd64.tar.gz
            incus exec {{ backend_container }} -- echo 'export PATH=$PATH:/usr/local/go/bin' >> /root/.bashrc
          register: go_install_result
          failed_when: false

        - name: Create backend application directory
          command: |
            incus exec {{ backend_container }} -- mkdir -p /opt/veza-backend
          register: backend_dir_result
          failed_when: false

        - name: Create simple backend server
          copy:
            content: |
              package main

              import (
                  "fmt"
                  "log"
                  "net/http"
                  "os"
              )

              func main() {
                  port := os.Getenv("PORT")
                  if port == "" {
                      port = "8080"
                  }

                  http.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
                      w.Header().Set("Content-Type", "application/json")
                      w.WriteHeader(http.StatusOK)
                      fmt.Fprintf(w, `{"status":"ok","service":"veza-backend"}`)
                  })

                  http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
                      w.Header().Set("Content-Type", "application/json")
                      w.WriteHeader(http.StatusOK)
                      fmt.Fprintf(w, `{"message":"Veza V5 Ultra Backend API","version":"1.0.0"}`)
                  })

                  log.Printf("Backend API server starting on port %s", port)
                  log.Fatal(http.ListenAndServe(":"+port, nil))
              }
            dest: /tmp/main.go
          delegate_to: localhost

        - name: Copy backend code to container
          command: |
            incus file push /tmp/main.go {{ backend_container }}/opt/veza-backend/main.go
          register: backend_code_result
          failed_when: false

        - name: Build backend application
          command: |
            incus exec {{ backend_container }} -- bash -c "cd /opt/veza-backend && /usr/local/go/bin/go mod init veza-backend && /usr/local/go/bin/go build -ldflags '-s -w' -o veza-backend main.go"
          register: backend_build_result
          failed_when: false

        - name: Create backend systemd service
          copy:
            content: |
              [Unit]
              Description=Veza V5 Ultra Backend API
              After=network.target

              [Service]
              Type=simple
              User=root
              WorkingDirectory=/opt/veza-backend
              ExecStart=/opt/veza-backend/veza-backend
              Restart=always
              RestartSec=5
              Environment=PORT=8080
              Environment=DATABASE_URL=postgresql://veza:password@localhost:5432/veza_db
              Environment=REDIS_URL=redis://localhost:6379
              Environment=JWT_SECRET=super-secret-jwt-key
              Environment=JWT_REFRESH_SECRET=super-secret-refresh-key

              [Install]
              WantedBy=multi-user.target
            dest: /tmp/veza-backend.service
          delegate_to: localhost

        - name: Copy systemd service to container
          command: |
            incus file push /tmp/veza-backend.service {{ backend_container }}/etc/systemd/system/veza-backend.service
          register: backend_service_result
          failed_when: false

        - name: Start backend service
          command: |
            incus exec {{ backend_container }} -- systemctl daemon-reload
            incus exec {{ backend_container }} -- systemctl enable veza-backend
            incus exec {{ backend_container }} -- systemctl start veza-backend
          register: backend_start_result
          failed_when: false

        - name: Check backend service status
          command: |
            incus exec {{ backend_container }} -- systemctl status veza-backend
          register: backend_status
          failed_when: false

        - name: Display backend status
          debug:
            var: backend_status.stdout_lines

      rescue:
        - name: Backend deployment failed
          debug:
            msg: "Backend deployment failed, continuing with other services"

    - name: Deploy simple web application
      block:
        - name: Install Node.js in web container
          command: |
            incus exec {{ web_container }} -- apt update
            incus exec {{ web_container }} -- apt install -y curl nginx
            incus exec {{ web_container }} -- curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
            incus exec {{ web_container }} -- apt install -y nodejs
          register: node_install_result
          failed_when: false

        - name: Create web application directory
          command: |
            incus exec {{ web_container }} -- mkdir -p /var/www/veza
          register: web_dir_result
          failed_when: false

        - name: Create simple web page
          copy:
            content: |
              <!DOCTYPE html>
              <html>
              <head>
                  <title>Veza V5 Ultra</title>
                  <style>
                      body { font-family: Arial, sans-serif; margin: 40px; }
                      .container { max-width: 800px; margin: 0 auto; }
                      .header { background: #2c3e50; color: white; padding: 20px; border-radius: 5px; }
                      .content { padding: 20px; }
                      .status { background: #27ae60; color: white; padding: 10px; border-radius: 3px; margin: 10px 0; }
                  </style>
              </head>
              <body>
                  <div class="container">
                      <div class="header">
                          <h1>🎵 Veza V5 Ultra</h1>
                          <p>Collaborative Audio Streaming Platform</p>
                      </div>
                      <div class="content">
                          <div class="status">✅ System Online</div>
                          <h2>Services Status</h2>
                          <ul>
                              <li>Backend API: <span id="api-status">Checking...</span></li>
                              <li>Chat WebSocket: <span id="chat-status">Checking...</span></li>
                              <li>Stream HLS: <span id="stream-status">Checking...</span></li>
                          </ul>
                          <h2>Features</h2>
                          <ul>
                              <li>Real-time collaborative audio streaming</li>
                              <li>WebSocket chat integration</li>
                              <li>HLS video streaming</li>
                              <li>Modern React frontend</li>
                          </ul>
                      </div>
                  </div>
                  <script>
                      // Simple health checks
                      fetch('/api/health').then(r => r.json()).then(d => {
                          document.getElementById('api-status').textContent = '✅ Online';
                      }).catch(() => {
                          document.getElementById('api-status').textContent = '❌ Offline';
                      });
                  </script>
              </body>
              </html>
            dest: /tmp/index.html
          delegate_to: localhost

        - name: Copy web page to container
          command: |
            incus file push /tmp/index.html {{ web_container }}/var/www/veza/index.html
          register: web_page_result
          failed_when: false

        - name: Configure nginx
          copy:
            content: |
              server {
                  listen 3000;
                  server_name _;
                  root /var/www/veza;
                  index index.html;

                  location / {
                      try_files $uri $uri/ =404;
                  }

                  location /api/ {
                      proxy_pass http://10.10.0.101:8080;
                      proxy_set_header Host $host;
                      proxy_set_header X-Real-IP $remote_addr;
                  }

                  location /ws {
                      proxy_pass http://10.10.0.102:8081;
                      proxy_http_version 1.1;
                      proxy_set_header Upgrade $http_upgrade;
                      proxy_set_header Connection "upgrade";
                      proxy_set_header Host $host;
                  }

                  location /stream/ {
                      proxy_pass http://10.10.0.103:8082;
                      proxy_set_header Host $host;
                  }
              }
            dest: /tmp/veza-nginx.conf
          delegate_to: localhost

        - name: Copy nginx config to container
          command: |
            incus file push /tmp/veza-nginx.conf {{ web_container }}/etc/nginx/sites-available/veza
          register: nginx_config_result
          failed_when: false

        - name: Enable nginx site
          command: |
            incus exec {{ web_container }} -- ln -sf /etc/nginx/sites-available/veza /etc/nginx/sites-enabled/
            incus exec {{ web_container }} -- rm -f /etc/nginx/sites-enabled/default
            incus exec {{ web_container }} -- systemctl restart nginx
          register: nginx_enable_result
          failed_when: false

        - name: Check web service status
          command: |
            incus exec {{ web_container }} -- systemctl status nginx
          register: web_status
          failed_when: false

        - name: Display web status
          debug:
            var: web_status.stdout_lines

      rescue:
        - name: Web deployment failed
          debug:
            msg: "Web deployment failed"

  post_tasks:
    - name: Clean up temporary files
      file:
        path: "{{ item }}"
        state: absent
      loop:
        - /tmp/main.go
        - /tmp/veza-backend.service
        - /tmp/index.html
        - /tmp/veza-nginx.conf
      delegate_to: localhost
      failed_when: false

    - name: Show all running services
      command: |
        incus exec {{ backend_container }} -- systemctl list-units --type=service --state=running | grep veza || true
        incus exec {{ web_container }} -- systemctl list-units --type=service --state=running | grep nginx || true
      register: all_services
      failed_when: false

    - name: Display all services
      debug:
        var: all_services.stdout_lines
