---
- name: Ensure bat package is installed
  tags: [packages]
  ansible.builtin.package:
    name: bat
    state: present

- name: Ensure XDG user directories exist
  tags: [dotfiles, dotfiles:common]
  ansible.builtin.file:
    path: "{{ effective_user_home }}/{{ item }}"
    state: directory
    owner: "{{ effective_username }}"
    group: "{{ effective_user_group }}"
    mode: "0755"
  loop: "{{ xdg_user_directories | default([]) }}"
  when: "'desktop' in group_names"

- name: Extract templates kit to Templates directory
  tags: [dotfiles, dotfiles:common]
  ansible.builtin.unarchive:
    src: "{{ playbook_dir }}/../dotfiles/common/templates_kit.zip"
    dest: "{{ effective_user_home }}/Templates"
    owner: "{{ effective_username }}"
    group: "{{ effective_user_group }}"
  when: "'desktop' in group_names"

- name: Ensure SSH socket directory exists
  tags: [dotfiles, dotfiles:common]
  ansible.builtin.file:
    path: "{{ effective_user_home }}/.local/state/ssh/sockets"
    state: directory
    owner: "{{ effective_username }}"
    group: "{{ effective_user_group }}"
    mode: "0700"

- name: Copy common dotfiles
  tags: [dotfiles, dotfiles:common]
  ansible.builtin.copy:
    src: "{{ playbook_dir }}/../dotfiles/common/{{ item.src }}"
    dest: "{{ effective_user_home }}/{{ item.dest }}"
    owner: "{{ effective_username }}"
    group: "{{ effective_user_group }}"
    mode: "{{ item.mode }}"
  loop: >-
    {{
      (common_dotfiles | default([]))
      + ((ai_agents_dotfiles | default([])) if (ai_agents_enabled | default(false)) else [])
    }}
  loop_control:
    label: "{{ item.dest }}"

- name: Ensure AI config directories exist
  tags: [dotfiles, dotfiles:common]
  ansible.builtin.file:
    path: "{{ effective_user_home }}/{{ item }}"
    state: directory
    owner: "{{ effective_username }}"
    group: "{{ effective_user_group }}"
    mode: "0755"
  loop:
    - .codex
  when:
    - ai_agents_enabled | default(false)
    - (ai_agents_templates | default([])) | length > 0

- name: Render AI agent templates
  tags: [dotfiles, dotfiles:common]
  ansible.builtin.template:
    src: "{{ playbook_dir }}/../dotfiles/common/{{ item.src }}"
    dest: "{{ effective_user_home }}/{{ item.dest }}"
    owner: "{{ effective_username }}"
    group: "{{ effective_user_group }}"
    mode: "{{ item.mode }}"
  loop: "{{ ai_agents_templates | default([]) }}"
  loop_control:
    label: "{{ item.dest }}"
  when: ai_agents_enabled | default(false)

- name: Refresh bat cache
  tags: [dotfiles, dotfiles:common]
  ansible.builtin.command:
    cmd: "{{ 'batcat' if ansible_facts.os_family == 'Debian' else 'bat' }} cache --build"
  become_user: "{{ effective_username }}"
  environment:
    HOME: "{{ effective_user_home }}"
  changed_when: false
