clickup 0.3.0

Cliente completo da API ClickUp com funcionalidades avançadas (smart search, fuzzy matching)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
use crate::client::ClickUpClient;
use crate::error::{ClickUpError, Result};
use chrono::{Datelike, Utc};
use serde::Deserialize;
use serde_json::Value;
/// Smart Folder Finder: Busca inteligente de folder_id usando API do ClickUp
///
/// ESTRATÉGIA ROBUSTA E GENÉRICA:
/// 1. **API Search**: GET folders do ClickUp + fuzzy matching semântico por nome
/// 2. **Historical Fallback**: DESCONTINUADO (sem dependência de campos customizados)
/// 3. **Generic Field Support**: Funciona com qualquer campo customizado como string
///
/// PRINCIPAIS FUNCIONALIDADES:
/// - `find_folder_for_client()`: Busca usando nome do cliente (original)
/// - `find_folder_by_extracted_value()`: Busca usando valor pré-extraído (NOVO)
/// - `find_folder_from_task_field()`: Busca extraindo campo de tarefa (NOVO)
/// - `extract_custom_field_value()`: Helper para extrair valores de campos (NOVO)
///
/// LÓGICA DE BUSCA POR NOME (sem dependência de campos customizados):
/// - Recebe string do cliente (extraída de info_2 ou qualquer outro campo)
/// - Compara APENAS pelo nome da pasta, usando similaridade de strings
/// - NÃO utiliza campos customizados das tarefas para determinação de estrutura
///
/// RETORNA:
/// - folder_id: ID da pasta encontrada
/// - list_id: ID da lista do mês atual (ou cria se não existir)
/// - confidence: Nível de confiança da busca (1.0 = exact, 0.70+ = fuzzy)
/// - search_method: Método usado (ExactMatch, FuzzyMatch, SemanticMatch)
use std::collections::HashMap;

// REMOVED: CLIENT_SOLICITANTE_FIELD_ID constant
// Reason: Campo "Cliente Solicitante" foi descontinuado do sistema
const FUZZY_THRESHOLD: f64 = 0.70; // Reduzido de 0.85 para 0.70

/// Deserializa ID que pode vir como string ou integer da API do ClickUp
fn deserialize_id_flexible<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::{self, Deserialize};

    let value = Value::deserialize(deserializer)?;
    match value {
        Value::String(s) => Ok(s),
        Value::Number(n) => Ok(n.to_string()),
        _ => Err(de::Error::custom("id must be string or number")),
    }
}
#[allow(dead_code)]
const MIN_HISTORICAL_CONFIDENCE: f64 = 0.5;

#[derive(Debug, Clone)]
pub struct FolderSearchResult {
    pub folder_id: String,
    pub folder_name: String,
    pub list_id: Option<String>,
    pub list_name: Option<String>,
    pub confidence: f64,
    pub search_method: SearchMethod,
}

#[derive(Debug, Clone, PartialEq)]
pub enum SearchMethod {
    ExactMatch,      // Nome exato encontrado
    FuzzyMatch,      // Similaridade >= 0.85
    SemanticMatch,   // Busca semântica (embeddings)
    HistoricalMatch, // Encontrado em tarefas anteriores
    NotFound,        // Não encontrado (usar fallback)
}

/// Estrutura de resposta da API do ClickUp para folders
#[derive(Debug, Deserialize)]
struct ClickUpFoldersResponse {
    folders: Vec<ClickUpFolder>,
}

#[derive(Debug, Deserialize, Clone)]
struct ClickUpFolder {
    #[serde(deserialize_with = "deserialize_id_flexible")]
    id: String,
    name: String,
    #[allow(dead_code)]
    lists: Option<Vec<ClickUpList>>,
}

#[derive(Debug, Deserialize, Clone)]
struct ClickUpList {
    #[serde(deserialize_with = "deserialize_id_flexible")]
    #[allow(dead_code)]
    id: String,
    #[allow(dead_code)]
    name: String,
}

/// Estrutura de resposta da API do ClickUp para tasks
#[derive(Debug, Deserialize)]
struct ClickUpTasksResponse {
    tasks: Vec<ClickUpTask>,
}

#[derive(Debug, Deserialize)]
struct ClickUpTask {
    #[serde(deserialize_with = "deserialize_id_flexible")]
    #[allow(dead_code)]
    id: String,
    #[allow(dead_code)]
    name: Option<String>,
    #[allow(dead_code)]
    folder: Option<ClickUpTaskFolder>,
    #[allow(dead_code)]
    list: Option<ClickUpTaskList>,
    #[allow(dead_code)]
    custom_fields: Option<Vec<ClickUpCustomField>>,
}

#[derive(Debug, Deserialize)]
struct ClickUpTaskFolder {
    #[serde(deserialize_with = "deserialize_id_flexible")]
    #[allow(dead_code)]
    id: String,
    #[allow(dead_code)]
    name: String,
}

#[derive(Debug, Deserialize)]
struct ClickUpTaskList {
    #[allow(dead_code)]
    #[serde(deserialize_with = "deserialize_id_flexible")]
    id: String,
    #[allow(dead_code)]
    name: String,
}

#[derive(Debug, Deserialize)]
pub struct ClickUpCustomField {
    #[allow(dead_code)]
    id: String,
    #[allow(dead_code)]
    value: Option<serde_json::Value>,
}

#[derive(Debug)]
pub struct SmartFolderFinder {
    client: ClickUpClient,
    workspace_id: String,
    cache: HashMap<String, FolderSearchResult>,
}

impl SmartFolderFinder {
    /// Criar novo finder
    pub fn new(client: ClickUpClient, workspace_id: String) -> Self {
        Self {
            client,
            workspace_id,
            cache: HashMap::new(),
        }
    }

    /// Criar novo finder a partir de API token (conveniência)
    pub fn from_token(api_token: String, workspace_id: String) -> Result<Self> {
        let client = ClickUpClient::new(api_token)?;
        Ok(Self::new(client, workspace_id))
    }

    /// Busca inteligente de folder por nome do cliente
    ///
    /// LÓGICA DE BUSCA POR NOME (sem dependência de campos customizados):
    /// - Recebe o nome do cliente (extraído de qualquer campo como info_2) pelo worker/core
    /// - Compara APENAS pelo nome da pasta, usando similaridade de string
    /// - NÃO utiliza campos customizados das tarefas para determinação de estrutura
    ///
    /// Fases:
    /// 1. Cache lookup (se já buscou antes)
    /// 2. API search com fuzzy matching por nome de pasta
    /// 3. Historical search DESCONTINUADO (campo personalizado removido)
    /// 4. Fallback (retorna None)
    pub async fn find_folder_for_client(
        &mut self,
        client_name: &str,
    ) -> Result<Option<FolderSearchResult>> {
        let normalized_name = Self::normalize_name(client_name);

        tracing::info!(
            "🔍 SmartFolderFinder: Buscando folder para '{}'",
            client_name
        );

        // 1. Cache lookup
        if let Some(cached) = self.cache.get(&normalized_name) {
            tracing::info!("✅ Encontrado em cache: folder_id={}", cached.folder_id);
            return Ok(Some(cached.clone()));
        }

        // 2. API Search (folders)
        match self.search_folders_via_api(&normalized_name).await {
            Ok(Some(result)) => {
                self.cache.insert(normalized_name.clone(), result.clone());
                return Ok(Some(result));
            }
            Ok(None) => {
                tracing::info!("⚠️ Não encontrado via API, tentando busca histórica...");
            }
            Err(e) => {
                tracing::warn!(
                    "⚠️ Erro na busca via API: {}, tentando busca histórica...",
                    e
                );
            }
        }

        // 3. Historical Search (FUNCIONALIDADE DESCONTINUADA)
        match self.search_historical_tasks(&normalized_name).await {
            Ok(Some(result)) => {
                self.cache.insert(normalized_name.clone(), result.clone());
                return Ok(Some(result));
            }
            Ok(None) => {
                tracing::warn!(
                    "⚠️ Cliente '{}' não encontrado (nem API, nem histórico)",
                    client_name
                );
            }
            Err(e) => {
                tracing::error!("❌ Erro na busca histórica: {}", e);
            }
        }

        // 4. Fallback
        Ok(None)
    }

    /// Nova funcionalidade: Busca inteligente de folder usando string extraída de campo customizado
    ///
    /// LÓGICA GENÉRICA PARA QUALQUER CAMPO:
    /// - Recebe uma string extraída pelo worker/core de qualquer campo (info_2, outro campo, etc.)
    /// - Esta função é independente do tipo/nome do campo original
    /// - A extração do valor do campo deve ser feita ANTES de chamar este método
    ///
    /// VANTAGENS:
    /// - Totalmente desacoplada de campos específicos
    /// - Funciona com qualquer campo customizado do ClickUp
    /// - Reutiliza toda a lógica de fuzzy matching existente
    /// - Mantém compatibilidade com API de folders
    ///
    /// EXEMPLO DE USO:
    /// ```no_run
    /// # use clickup::folders::SmartFolderFinder;
    /// # use clickup::client::ClickUpClient;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = ClickUpClient::new("your_api_token".to_string())?;
    /// let mut finder = SmartFolderFinder::new(client, "workspace_id".to_string());
    /// let client_name = "ACME Corporation";
    /// let result = finder.find_folder_by_extracted_value(&client_name).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn find_folder_by_extracted_value(
        &mut self,
        extracted_value: &str,
    ) -> Result<Option<FolderSearchResult>> {
        tracing::info!(
            "🔍 SmartFolderFinder: Buscando folder usando valor extraído: '{}'",
            extracted_value
        );

        // Reutiliza toda a lógica existente de find_folder_for_client
        // Isso garante consistência e evita duplicação de código
        self.find_folder_for_client(extracted_value).await
    }

    /// Método auxiliar para extração de valor de campo customizado específico
    ///
    /// PROPÓSITO: Demonstra como extrair valores de campos customizados
    /// NOTA: Este método deve ser usado pelo worker/core ANTES de chamar find_folder_by_extracted_value
    ///
    /// PARÂMETROS:
    /// - custom_fields: Array de campos customizados da tarefa
    /// - target_field_id: ID do campo a ser extraído (ex: "info_2", ou qualquer outro)
    ///
    /// RETORNO: Option<String> com o valor do campo, se encontrado
    pub fn extract_custom_field_value(
        custom_fields: &[ClickUpCustomField],
        target_field_id: &str,
    ) -> Option<String> {
        for field in custom_fields {
            if field.id == target_field_id {
                if let Some(value) = &field.value {
                    // Converter valor JSON para string
                    match value {
                        serde_json::Value::String(s) => return Some(s.clone()),
                        serde_json::Value::Number(n) => return Some(n.to_string()),
                        serde_json::Value::Bool(b) => return Some(b.to_string()),
                        serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
                            return Some(value.to_string());
                        }
                        serde_json::Value::Null => return None,
                    }
                }
            }
        }
        None
    }

    /// Método de conveniência: busca folder usando campo específico de uma tarefa
    ///
    /// WORKFLOW COMPLETO:
    /// 1. Extrai valor do campo customizado especificado
    /// 2. Se encontrado, busca folder usando o valor
    /// 3. Retorna resultado da busca
    ///
    /// EXEMPLO DE USO:
    /// ```no_run
    /// # use clickup::folders::SmartFolderFinder;
    /// # use clickup::client::ClickUpClient;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = ClickUpClient::new("your_api_token".to_string())?;
    /// let mut finder = SmartFolderFinder::new(client, "workspace_id".to_string());
    /// let custom_fields = vec![];
    /// let result = finder.find_folder_from_task_field(Some(&custom_fields), "info_2_field_id").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn find_folder_from_task_field(
        &mut self,
        custom_fields: Option<&Vec<ClickUpCustomField>>,
        field_id: &str,
    ) -> Result<Option<FolderSearchResult>> {
        tracing::info!(
            "🔍 Extraindo valor do campo '{}' para busca de folder",
            field_id
        );

        if let Some(fields) = custom_fields {
            if let Some(extracted_value) = Self::extract_custom_field_value(fields, field_id) {
                tracing::info!("✅ Valor extraído: '{}'", extracted_value);
                return self.find_folder_by_extracted_value(&extracted_value).await;
            }
        }

        tracing::warn!("⚠️ Campo '{}' não encontrado ou vazio", field_id);
        Ok(None)
    }

    /// Fase 1: Buscar folders via API do ClickUp
    async fn search_folders_via_api(
        &self,
        normalized_client: &str,
    ) -> Result<Option<FolderSearchResult>> {
        tracing::info!("📡 Buscando folders via API do ClickUp...");

        // GET /team/{team_id}/space (API v2)
        // Nota: Na v2, usa-se "team" mas internamente chamamos de "workspace" para clareza
        // Como não sabemos o space_id, vamos buscar em todos os spaces

        let endpoint = format!("/team/{}/space", self.workspace_id);
        let spaces: serde_json::Value = self.client.get_json(&endpoint).await?;

        let spaces_array = spaces["spaces"].as_array().ok_or_else(|| {
            ClickUpError::ValidationError("Campo 'spaces' não é array".to_string())
        })?;

        // Para cada space, buscar folders
        let mut all_folders = Vec::new();
        for space in spaces_array {
            let space_id = space["id"]
                .as_str()
                .ok_or_else(|| ClickUpError::ValidationError("Space sem ID".to_string()))?;

            match self.fetch_folders_from_space(space_id).await {
                Ok(folders) => all_folders.extend(folders),
                Err(e) => {
                    tracing::warn!("⚠️ Erro ao buscar folders do space {}: {}", space_id, e);
                }
            }
        }

        tracing::info!("📁 Total de folders encontrados: {}", all_folders.len());

        // Buscar melhor match usando fuzzy matching
        self.find_best_folder_match(normalized_client, &all_folders)
            .await
    }

    /// Buscar folders de um space específico
    async fn fetch_folders_from_space(&self, space_id: &str) -> Result<Vec<ClickUpFolder>> {
        let endpoint = format!("/space/{}/folder", space_id);
        let folders_response: ClickUpFoldersResponse = self.client.get_json(&endpoint).await?;
        Ok(folders_response.folders)
    }

    /// Encontrar melhor match usando fuzzy matching
    ///
    /// ESTRATÉGIAS DE COMPARAÇÃO POR NOME:
    /// 1. Exact Match: Nomes normalizados idênticos (confiança 1.0)
    /// 2. Fuzzy Match: Jaro-Winkler >= 0.70 entre nomes normalizados
    /// 3. Token Match: 60%+ dos tokens principais coincidem (para "Breno/Leticia" vs "Leticia e Breno")
    ///
    /// MOTIVAÇÃO: Garante que a busca é baseada SOMENTE no nome da pasta do ClickUp,
    /// sem depender de metadados ou campos customizados das tarefas.
    async fn find_best_folder_match(
        &self,
        normalized_client: &str,
        folders: &[ClickUpFolder],
    ) -> Result<Option<FolderSearchResult>> {
        let mut best_match: Option<(ClickUpFolder, f64, SearchMethod)> = None;

        for folder in folders {
            let normalized_folder = Self::normalize_name(&folder.name);

            // 1. Exact match
            if normalized_folder == normalized_client {
                tracing::info!("✅ Match exato: '{}'", folder.name);
                best_match = Some((folder.clone(), 1.0, SearchMethod::ExactMatch));
                break;
            }

            // 2. Fuzzy match (Jaro-Winkler)
            let similarity = strsim::jaro_winkler(normalized_client, &normalized_folder);

            tracing::debug!(
                "  Comparando: '{}' vs '{}' → score: {:.3}",
                normalized_client,
                normalized_folder,
                similarity
            );

            if similarity >= FUZZY_THRESHOLD {
                if let Some((_, best_score, _)) = &best_match {
                    if similarity > *best_score {
                        best_match = Some((folder.clone(), similarity, SearchMethod::FuzzyMatch));
                    }
                } else {
                    best_match = Some((folder.clone(), similarity, SearchMethod::FuzzyMatch));
                }
            }

            // 3. Token-based matching (para casos como "Breno / Leticia" → "Leticia e Breno")
            // Verifica se os principais tokens estão presentes, independente da ordem
            if best_match.is_none()
                || best_match
                    .as_ref()
                    .map(|(_, score, _)| *score)
                    .unwrap_or(0.0)
                    < 0.90
            {
                let client_tokens = Self::extract_name_tokens(normalized_client);
                let folder_tokens = Self::extract_name_tokens(&normalized_folder);

                if !client_tokens.is_empty() && !folder_tokens.is_empty() {
                    let matching_tokens = client_tokens
                        .iter()
                        .filter(|ct| {
                            folder_tokens
                                .iter()
                                .any(|ft| strsim::jaro_winkler(ct, ft) >= 0.90)
                        })
                        .count();

                    let token_score = matching_tokens as f64
                        / client_tokens.len().max(folder_tokens.len()) as f64;

                    if token_score >= 0.60 {
                        // Pelo menos 60% dos tokens devem dar match
                        tracing::debug!(
                            "  Token match: {}/{} tokens → score: {:.3}",
                            matching_tokens,
                            client_tokens.len().max(folder_tokens.len()),
                            token_score
                        );

                        if let Some((_, best_score, _)) = &best_match {
                            if token_score > *best_score {
                                best_match =
                                    Some((folder.clone(), token_score, SearchMethod::FuzzyMatch));
                            }
                        } else {
                            best_match =
                                Some((folder.clone(), token_score, SearchMethod::FuzzyMatch));
                        }
                    }
                }
            }
        }

        if let Some((folder, score, method)) = best_match {
            // Buscar lista do mês atual
            let (list_id, list_name) = self.find_or_create_current_month_list(&folder.id).await?;

            Ok(Some(FolderSearchResult {
                folder_id: folder.id,
                folder_name: folder.name,
                list_id: Some(list_id),
                list_name: Some(list_name),
                confidence: score,
                search_method: method,
            }))
        } else {
            Ok(None)
        }
    }

    /// Fase 2: Buscar em tarefas anteriores (FUNCIONALIDADE DESCONTINUADA)
    ///
    /// MOTIVAÇÃO DA DESCONTINUAÇÃO:
    /// - Campo "Cliente Solicitante" foi removido do sistema
    /// - Busca agora depende EXCLUSIVAMENTE dos nomes das pastas (API /folder)
    /// - Eliminada dependência de campos customizados para determinação de estrutura
    ///
    /// IMPACTO: Sistema mais robusto e independente de configurações de campos personalizados
    async fn search_historical_tasks(
        &self,
        normalized_client: &str,
    ) -> Result<Option<FolderSearchResult>> {
        tracing::info!(
            "🕐 Buscando tarefas históricas para cliente = '{}' (funcionalidade descontinuada)",
            normalized_client
        );

        // GET /team/{team_id}/task with query params (API v2)
        // Nota: Na v2, usa-se "team" mas internamente chamamos de "workspace"
        let endpoint = format!(
            "/team/{}/task?archived=false&subtasks=false&include_closed=true",
            self.workspace_id
        );
        let tasks_response: ClickUpTasksResponse = self.client.get_json(&endpoint).await?;

        tracing::info!(
            "📋 Total de tarefas encontradas: {}",
            tasks_response.tasks.len()
        );

        // FUNCIONALIDADE DESCONTINUADA: Campo "Cliente Solicitante" foi removido
        // Retorna imediatamente None pois não há mais campo para buscar
        tracing::warn!(
            "⚠️ Busca histórica descontinuada - campo 'Cliente Solicitante' removido do sistema"
        );
        Ok(None)

        // Código original removido em 2025-11-07:
        // - Loop através de tasks_response.tasks
        // - Verificação de field.id == CLIENT_SOLICITANTE_FIELD_ID (constante removida)
        // - Fuzzy matching via strsim::jaro_winkler()
        // - Retorno de FolderSearchResult com SearchMethod::HistoricalMatch
        
        /*
        for task in tasks_response.tasks {
            if let Some(custom_fields) = task.custom_fields {
                for field in custom_fields {
                    // REMOVIDO: if field.id == CLIENT_SOLICITANTE_FIELD_ID {
                    // ... resto do código removido
                    }
                }
            }
        }
        */
    }

    /// Gera nome do mês em português e caixa alta (ex: "OUTUBRO 2025")
    fn get_month_name_pt(&self, date: chrono::DateTime<Utc>) -> String {
        let month = date.month();
        let year = date.year();

        let month_pt = match month {
            1 => "JANEIRO",
            2 => "FEVEREIRO",
            3 => "MARÇO",
            4 => "ABRIL",
            5 => "MAIO",
            6 => "JUNHO",
            7 => "JULHO",
            8 => "AGOSTO",
            9 => "SETEMBRO",
            10 => "OUTUBRO",
            11 => "NOVEMBRO",
            12 => "DEZEMBRO",
            _ => "DESCONHECIDO",
        };

        format!("{} {}", month_pt, year)
    }

    /// Buscar ou criar lista do mês atual na folder
    async fn find_or_create_current_month_list(&self, folder_id: &str) -> Result<(String, String)> {
        let now = Utc::now();
        let month_name_pt = self.get_month_name_pt(now); // Ex: "OUTUBRO 2025"
        let month_number = now.month();

        tracing::info!("📅 Buscando lista do mês atual: '{}'", month_name_pt);

        // GET /folder/{folder_id}
        let endpoint = format!("/folder/{}", folder_id);
        let folder: serde_json::Value = self.client.get_json(&endpoint).await?;

        // Meses em português para busca (aceita variações)
        let months_pt = [
            "janeiro",
            "fevereiro",
            "março",
            "abril",
            "maio",
            "junho",
            "julho",
            "agosto",
            "setembro",
            "outubro",
            "novembro",
            "dezembro",
        ];
        let current_month_pt = months_pt[(month_number - 1) as usize];
        let year_str = now.year().to_string();

        // Buscar lista com nome do mês (aceita em português ou inglês, case-insensitive)
        if let Some(lists) = folder["lists"].as_array() {
            for list in lists {
                if let Some(name) = list["name"].as_str() {
                    let name_lower = name.to_lowercase();

                    // Aceita: "OUTUBRO 2025", "outubro 2025", "October 2025", etc.
                    if (name_lower.contains(current_month_pt)
                        || name_lower.contains(&now.format("%B").to_string().to_lowercase()))
                        && name_lower.contains(&year_str)
                    {
                        let list_id = list["id"].as_str().ok_or_else(|| {
                            ClickUpError::ValidationError("Lista sem ID".to_string())
                        })?;

                        tracing::info!("✅ Lista do mês encontrada: {} (id: {})", name, list_id);
                        return Ok((list_id.to_string(), name.to_string()));
                    }
                }
            }
        }

        // Lista não encontrada, criar nova em português e caixa alta
        tracing::info!("📝 Criando lista do mês: '{}'", month_name_pt);
        self.create_list(folder_id, &month_name_pt).await
    }

    /// Criar lista na folder
    async fn create_list(&self, folder_id: &str, list_name: &str) -> Result<(String, String)> {
        let endpoint = format!("/folder/{}/list", folder_id);
        let payload = serde_json::json!({
            "name": list_name,
            "content": format!("Lista criada automaticamente para {}", list_name),
        });

        let list: serde_json::Value = self.client.post_json(&endpoint, &payload).await?;

        let list_id = list["id"]
            .as_str()
            .ok_or_else(|| ClickUpError::ValidationError("Lista criada sem ID".to_string()))?;

        tracing::info!(
            "✅ Lista criada com sucesso: {} (id: {})",
            list_name,
            list_id
        );

        // Aguardar 2 segundos para ClickUp configurar custom fields da lista
        tracing::debug!("⏳ Aguardando 2s para custom fields serem configurados...");
        tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;

        Ok((list_id.to_string(), list_name.to_string()))
    }

    /// Normalizar nome: lowercase, remover acentos, números e pontuação
    pub fn normalize_name(name: &str) -> String {
        use deunicode::deunicode;

        // Substituir "/" e outros separadores por espaço antes de processar
        let normalized = name.replace(['/', '\\', '|', '-'], " ");

        // Remover acentos, converter para lowercase, remover caracteres especiais
        deunicode(&normalized)
            .to_lowercase()
            .chars()
            .filter(|c| c.is_alphanumeric() || c.is_whitespace())
            .collect::<String>()
            .split_whitespace()
            .collect::<Vec<&str>>()
            .join(" ")
    }

    /// Extrai tokens individuais de um nome para matching mais flexível
    /// Exemplo: "Breno / Leticia" → ["breno", "leticia"]
    fn extract_name_tokens(name: &str) -> Vec<String> {
        Self::normalize_name(name)
            .split_whitespace()
            .filter(|token| token.len() > 2) // Ignorar tokens muito curtos como "e", "de"
            .map(|s| s.to_string())
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_normalize_name() {
        assert_eq!(
            SmartFolderFinder::normalize_name("Raphaela Spielberg"),
            "raphaela spielberg"
        );
        assert_eq!(
            SmartFolderFinder::normalize_name("José Muritiba (123)"),
            "jose muritiba 123"
        );
        assert_eq!(
            SmartFolderFinder::normalize_name("Gabriel Benarros!!!"),
            "gabriel benarros"
        );

        // Novos testes para "/" e separadores
        assert_eq!(
            SmartFolderFinder::normalize_name("Breno / Leticia"),
            "breno leticia"
        );
        assert_eq!(
            SmartFolderFinder::normalize_name("Leticia e Breno"),
            "leticia e breno"
        );
        assert_eq!(
            SmartFolderFinder::normalize_name("Carlos | Pedro"),
            "carlos pedro"
        );
        assert_eq!(SmartFolderFinder::normalize_name("Ana-Paula"), "ana paula");
    }

    #[test]
    fn test_extract_name_tokens() {
        let tokens = SmartFolderFinder::extract_name_tokens("Breno / Leticia");
        assert_eq!(tokens, vec!["breno", "leticia"]);

        let tokens2 = SmartFolderFinder::extract_name_tokens("Leticia e Breno");
        assert_eq!(tokens2, vec!["leticia", "breno"]);

        let tokens3 = SmartFolderFinder::extract_name_tokens("José de Oliveira");
        assert_eq!(tokens3, vec!["jose", "oliveira"]); // "de" é filtrado por ser muito curto
    }

    #[test]
    fn test_extract_custom_field_value() {
        use serde_json::Value;

        // Simular campos customizados
        let custom_fields = vec![
            ClickUpCustomField {
                id: "info_1".to_string(),
                value: Some(Value::String("Valor Info 1".to_string())),
            },
            ClickUpCustomField {
                id: "info_2".to_string(),
                value: Some(Value::String("João Silva".to_string())),
            },
            ClickUpCustomField {
                id: "priority".to_string(),
                value: Some(Value::Number(serde_json::Number::from(3))),
            },
            ClickUpCustomField {
                id: "active".to_string(),
                value: Some(Value::Bool(true)),
            },
            ClickUpCustomField {
                id: "empty_field".to_string(),
                value: None,
            },
        ];

        // Teste: extrair campo string
        assert_eq!(
            SmartFolderFinder::extract_custom_field_value(&custom_fields, "info_2"),
            Some("João Silva".to_string())
        );

        // Teste: extrair campo numérico
        assert_eq!(
            SmartFolderFinder::extract_custom_field_value(&custom_fields, "priority"),
            Some("3".to_string())
        );

        // Teste: extrair campo booleano
        assert_eq!(
            SmartFolderFinder::extract_custom_field_value(&custom_fields, "active"),
            Some("true".to_string())
        );

        // Teste: campo não encontrado
        assert_eq!(
            SmartFolderFinder::extract_custom_field_value(&custom_fields, "inexistente"),
            None
        );

        // Teste: campo vazio
        assert_eq!(
            SmartFolderFinder::extract_custom_field_value(&custom_fields, "empty_field"),
            None
        );
    }
}