- name: Ensure Lab 1 model directory exists
  file:
    path: "{{ courseware_lab1_models_dir }}"
    state: directory
    mode: "0755"

- name: Check installed Ollama version
  command:
    argv:
      - "{{ courseware_ollama_bin }}"
      - --version
  register: courseware_lab1_ollama_version
  changed_when: false

- name: Extract installed Ollama semantic version
  set_fact:
    courseware_lab1_ollama_semver: >-
      {{
        courseware_lab1_ollama_version.stdout
        | regex_search('[0-9]+\\.[0-9]+\\.[0-9]+')
        | default('')
      }}

- name: Fail when Ollama is too old for Lab 1 logprobs
  fail:
    msg: >-
      Lab 1 requires Ollama {{ courseware_ollama_min_version }} or newer because
      the confidence visualizer depends on logprob support. Installed version:
      {{ courseware_lab1_ollama_version.stdout | trim }}.
  when:
    - courseware_lab1_ollama_semver | length == 0
      or not (courseware_lab1_ollama_semver is version(courseware_ollama_min_version, '>='))

- name: Download mirrored Lab 1 Qwen model
  get_url:
    url: "{{ courseware_lab1_qwen_download_url }}"
    dest: "{{ courseware_lab1_qwen_local_path }}"
    mode: "0644"

- name: Download mirrored Lab 1 Llama model
  get_url:
    url: "{{ courseware_lab1_llama_download_url }}"
    dest: "{{ courseware_lab1_llama_local_path }}"
    mode: "0644"

- name: Write Lab 1 Ollama Modelfile
  copy:
    dest: "{{ courseware_lab1_dir }}/Modelfile.{{ courseware_lab1_qwen_model_alias }}"
    mode: "0644"
    content: |
      FROM {{ courseware_lab1_qwen_local_path }}

- name: Start Ollama before Lab 1 model registration
  command:
    argv:
      - "{{ courseware_root }}/scripts/service_manager.sh"
      - start
      - ollama
  changed_when: false

- name: Register Lab 1 Qwen model with Ollama
  command:
    argv:
      - "{{ courseware_ollama_bin }}"
      - create
      - "{{ courseware_lab1_qwen_model_alias }}"
      - -f
      - "{{ courseware_lab1_dir }}/Modelfile.{{ courseware_lab1_qwen_model_alias }}"
  environment:
    OLLAMA_HOST: "{{ courseware_bind_host }}:{{ courseware_ports.ollama }}"
    OLLAMA_MODELS: "{{ courseware_ollama_models_dir }}"
