- name: Create managed state directories
  file:
    path: "{{ item }}"
    state: directory
    mode: "0755"
  loop:
    - "{{ courseware_state_dir }}"
    - "{{ courseware_markers_dir }}"
    - "{{ courseware_logs_dir }}"
    - "{{ courseware_run_dir }}"
    - "{{ courseware_repos_dir }}"
    - "{{ courseware_venvs_dir }}"
    - "{{ courseware_models_dir }}"
    - "{{ courseware_datasets_dir }}"
    - "{{ courseware_tools_dir }}"
    - "{{ courseware_apps_dir }}"
    - "{{ courseware_downloads_dir }}"
    - "{{ courseware_lab2_dir }}"
    - "{{ courseware_safe_homes_dir }}"
    - "{{ courseware_transformerlab_home }}"
    - "{{ courseware_unsloth_home }}"
    - "{{ courseware_ollama_models_dir }}"

- name: Seed managed ownership markers
  file:
    path: "{{ item }}"
    state: touch
    mode: "0644"
  loop:
    - "{{ courseware_transformerlab_home }}/.courseware-managed"
    - "{{ courseware_unsloth_home }}/.courseware-managed"

- name: Check existing TransformerLab path
  stat:
    path: "{{ ansible_env.HOME }}/.transformerlab"
    follow: false
  register: courseware_transformerlab_link

- name: Check existing TransformerLab ownership marker
  stat:
    path: "{{ ansible_env.HOME }}/.transformerlab/.courseware-managed"
  register: courseware_transformerlab_marker

- name: Fail if TransformerLab path is already occupied
  fail:
    msg: "{{ ansible_env.HOME }}/.transformerlab already exists and is not managed by this project."
  when:
    - courseware_transformerlab_link.stat.exists
    - >
      (
        (not courseware_transformerlab_link.stat.islnk) or
        (courseware_transformerlab_link.stat.islnk and
         courseware_transformerlab_link.stat.lnk_source != courseware_transformerlab_home)
      ) and
      (not courseware_transformerlab_marker.stat.exists)

- name: Link TransformerLab home into project state
  file:
    src: "{{ courseware_transformerlab_home }}"
    dest: "{{ ansible_env.HOME }}/.transformerlab"
    state: link
    force: true

- name: Check existing Unsloth path
  stat:
    path: "{{ ansible_env.HOME }}/.unsloth"
    follow: false
  register: courseware_unsloth_link

- name: Fail if Unsloth path is already occupied
  fail:
    msg: "{{ ansible_env.HOME }}/.unsloth already exists and is not managed by this project."
  when:
    - courseware_unsloth_link.stat.exists
    - >
      (not courseware_unsloth_link.stat.islnk) or
      (courseware_unsloth_link.stat.islnk and
       courseware_unsloth_link.stat.lnk_source != courseware_unsloth_home)

- name: Link Unsloth home into project state
  file:
    src: "{{ courseware_unsloth_home }}"
    dest: "{{ ansible_env.HOME }}/.unsloth"
    state: link
    force: true

- name: Write runtime environment file
  template:
    src: "{{ playbook_dir }}/../templates/runtime.env.j2"
    dest: "{{ courseware_state_dir }}/runtime.env"
    mode: "0644"
