- name: Download Unsloth Studio installer
  get_url:
    url: "{{ courseware_unsloth_installer_url }}"
    dest: "{{ courseware_unsloth_installer_path }}"
    mode: "0755"

- name: Install Unsloth Studio
  block:
    - name: Run Unsloth Studio installer
      shell: |
        set -euo pipefail
        timeout "{{ courseware_unsloth_install_timeout_seconds }}" \
          bash "{{ courseware_unsloth_installer_path }}" --python "{{ courseware_unsloth_python_version }}" \
          > "{{ courseware_logs_dir }}/unsloth-install.log" 2>&1
        touch "{{ courseware_unsloth_home }}/.courseware-managed"
        touch "{{ courseware_unsloth_home }}/.install_complete"
      args:
        executable: /bin/bash
        creates: "{{ courseware_unsloth_home }}/.install_complete"
  rescue:
    - name: Capture Unsloth installer log tail
      shell: |
        if [ -f "{{ courseware_logs_dir }}/unsloth-install.log" ]; then
          tail -n 80 "{{ courseware_logs_dir }}/unsloth-install.log"
        fi
      args:
        executable: /bin/bash
      register: courseware_unsloth_install_log_tail
      changed_when: false
      failed_when: false

    - name: Fail with Unsloth installer guidance
      fail:
        msg: |
          Unsloth Studio install failed or timed out.

          Review the full log at:
            {{ courseware_logs_dir }}/unsloth-install.log

          The installer is pinned to Python {{ courseware_unsloth_python_version }} to avoid slower, less predictable dependency resolution on Linux/WSL.

          Last log lines:
          {{ courseware_unsloth_install_log_tail.stdout | default('(no log output captured)') }}
