{{- $apps := .chezmoi.config.data.apps -}}
{{- /* Resolve placement role -> monitor name, falling back to the primary monitor. */ -}}
{{- $primary := "" -}}
{{- range .monitors }}{{ if index . "primary" }}{{ $primary = .name }}{{ end }}{{ end -}}
{{- if not $primary }}{{ $primary = (index .monitors 0).name }}{{ end -}}
{{- $role2mon := dict -}}
{{- range .monitors }}{{ if hasKey . "role" }}{{ $role2mon = set $role2mon .role .name }}{{ end }}{{ end -}}

-- Special Workspaces
hl.workspace_rule({ workspace = "special:passwordmgr", on_created_empty = "uwsm app -- bitwarden-desktop" })

-- Named app-home workspaces (data-driven via .placement; monitor resolved from role)
{{- range $p := .placement }}
{{- if or (not (hasKey $p "requires")) (has $p.requires $apps) }}
hl.workspace_rule({ workspace = "{{ $p.id }}", default_name = "{{ $p.name }}", monitor = "{{ index $role2mon $p.role | default $primary }}"
  {{- if hasKey $p "layout" }}, layout = "{{ $p.layout }}"{{ end }}
  {{- if hasKey $p "layoutopts" }}, layout_opts = { {{ range $i, $opt := $p.layoutopts }}{{ $parts := splitList ":" $opt }}{{ if $i }}, {{ end }}{{ index $parts 0 }} = "{{ index $parts 1 }}"{{ end }} }{{ end }}
  {{- if hasKey $p "on_created_empty" }}, on_created_empty = "{{ $p.on_created_empty }}"{{ end }} })
{{- end }}
{{- end }}

-- Monitor Workspaces
{{- range $monitor := .monitors }}
  {{- range $index, $ws := $monitor.workspaces }}
    {{- if kindIs "map" $ws }}
hl.workspace_rule({ 
  workspace = "{{ $ws.id }}", 
  monitor = "{{ $monitor.name }}",
  default = {{ if eq $index 0 }}true{{ else }}false{{ end }}
  {{- if index $ws "name" }}, default_name = "{{ $ws.name }}"{{ end }}
  {{- if index $ws "layout" }}, layout = "{{ $ws.layout }}"{{ end }}
  {{- if index $ws "layoutopts" }}, layout_opts = {
    {{- range $i, $opt := index $ws "layoutopts" }}
    {{- $parts := splitList ":" $opt }}
    {{ if $i }}, {{ end }}{{ index $parts 0 }} = "{{ index $parts 1 }}"
    {{- end }}
  }{{ end }}
})
    {{- else }}
hl.workspace_rule({ workspace = "{{ $ws }}", monitor = "{{ $monitor.name }}", default = {{ if eq $index 0 }}true{{ else }}false{{ end }} })
    {{- end }}
  {{- end }}
{{- end }}
