---
# Ollama installation and setup

- name: Check if Ollama is already installed
  ansible.builtin.command: ollama --version
  register: ollama_version_check
  changed_when: false
  failed_when: false

- name: Install Ollama (Linux)
  ansible.builtin.shell: |
    curl -fsSL https://ollama.com/install.sh | sh
  when:
    - ansible_os_family == "Debian"
    - ollama_version_check.rc != 0
  become: yes
  notify: Start Ollama service

- name: Install Ollama (macOS via Homebrew)
  ansible.builtin.homebrew:
    name: ollama
    state: present
  when:
    - ansible_os_family == "Darwin"
    - ollama_version_check.rc != 0

- name: Check if Ollama service exists
  ansible.builtin.command: systemctl list-unit-files ollama.service
  register: ollama_service_check
  changed_when: false
  failed_when: false
  when: ansible_os_family == "Debian"

- name: Ensure Ollama service is running (Linux)
  ansible.builtin.systemd:
    name: ollama
    state: started
    enabled: yes
  become: yes
  when:
    - ansible_os_family == "Debian"
    - ollama_version_check.rc == 0
    - ollama_service_check.stdout is defined
    - "'ollama.service' in ollama_service_check.stdout"
  ignore_errors: yes

- name: Start Ollama manually if no systemd service
  ansible.builtin.shell: |
    pkill -f "ollama serve" 2>/dev/null || true
    nohup ollama serve > {{ llmlab_base }}/.llmlab/logs/ollama.log 2>&1 &
  when:
    - ansible_os_family == "Debian"
    - ollama_version_check.rc == 0
    - (ollama_service_check.stdout is not defined or "'ollama.service' not in ollama_service_check.stdout")
  become: no
  ignore_errors: yes

- name: Wait for Ollama to be ready
  ansible.builtin.wait_for:
    port: 11434
    delay: 5
    timeout: 60
  when: ollama_version_check.rc == 0

- name: Display Ollama version
  ansible.builtin.debug:
    msg: "Ollama installed: {{ ollama_version_check.stdout }}"
