kasl-cli 1.0.1

kasl is a comprehensive command-line utility 🛠️ designed to streamline the tracking of work activities 📊, including start times ⏰, pauses ⏸, and task completion
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Jira API integration for issue tracking and task synchronization.
//!
//! Provides functionality to connect to Jira instances and retrieve completed
//! issues for automatic task generation and time tracking integration.
//!
//! ## Features
//!
//! - **Issue Retrieval**: Fetch completed issues for specific dates
//! - **Session Management**: Automatic login and session token caching
//! - **Error Recovery**: Robust retry logic for authentication failures
//! - **JQL Integration**: Flexible issue querying using Jira Query Language
//!
//! ## Usage
//!
//! ```rust,no_run
//! # use kasl::api::jira::{Jira, JiraConfig};
//! # use chrono::Local;
//! # async fn f() -> anyhow::Result<()> {
//! let config = JiraConfig {
//!     login: "username".to_string(),
//!     api_url: "https://jira.company.com".to_string(),
//!     completed_statuses: Vec::new(),
//! };
//!
//! let mut jira = Jira::new(&config);
//! let today = Local::now().date_naive();
//! let issues = jira.get_completed_issues(&today).await?;
//! # Ok(())
//! # }
//! ```

use super::Session;
use crate::libs::{config::ConfigModule, messages::Message, secret::Secret};
use crate::msg_print;
use anyhow::Result;
use chrono::NaiveDate;
use dialoguer::{Input, theme::ColorfulTheme};
use reqwest::{
    Client, StatusCode,
    header::{COOKIE, HeaderMap, HeaderValue},
};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::time::Duration;

/// Maximum number of authentication retries before giving up.
/// This prevents infinite loops when credentials are consistently invalid.
const MAX_RETRY_COUNT: i32 = 3;

/// Page size for Jira issue search pagination.
const SEARCH_PAGE_SIZE: u32 = 100;

/// Filename for storing Jira session tokens in the user data directory.
const SESSION_ID_FILE: &str = ".jira_session_id";

/// Filename for storing encrypted Jira credentials for password caching.
const SECRET_FILE: &str = ".jira_secret";

/// Jira REST API endpoint for session-based authentication.
const AUTH_URL: &str = "rest/auth/1/session";

/// Jira REST API endpoint for issue searching using JQL queries.
const SEARCH_URL: &str = "rest/api/2/search";

/// User credentials for Jira authentication.
///
/// This structure holds the login information required for establishing
/// a session with the Jira API. Credentials are only held in memory
/// during the authentication process and are never persisted to disk.
///
/// ## Security Considerations
///
/// - Passwords are stored in plain text only during authentication
/// - Credentials are cleared from memory after session establishment
/// - No persistence to avoid credential theft from configuration files
#[derive(Serialize, Clone, Debug)]
pub struct LoginCredentials {
    /// Jira username (not email address unless configured as such)
    username: String,
    /// User password in plain text (only during auth process)
    password: String,
}

/// Response structure for Jira session authentication.
///
/// Contains the session information returned by Jira after successful
/// authentication, including the session cookie name and value that
/// must be used in subsequent API requests.
#[derive(Serialize, Deserialize, Debug)]
struct JiraSessionResponse {
    /// Session object containing cookie information
    session: JiraSession,
}

/// Jira session cookie information.
///
/// Represents the session cookie that must be included in subsequent
/// API requests to authenticate the user. This cookie typically expires
/// after a period of inactivity or when explicitly invalidated.
#[derive(Serialize, Deserialize, Debug)]
struct JiraSession {
    /// Cookie name (typically "JSESSIONID" for server instances)
    name: String,
    /// Cookie value (the actual session token)
    value: String,
}

/// Represents a Jira issue with essential fields for task creation.
///
/// This structure contains the core information needed to create tasks
/// from Jira issues, focusing on identification and descriptive content
/// rather than the full complexity of Jira's data model.
#[derive(Serialize, Deserialize, Debug)]
pub struct JiraIssue {
    /// Unique issue identifier assigned by Jira (numeric)
    pub id: String,
    /// Human-readable issue key (e.g., "PROJECT-123")
    pub key: String,
    /// Issue fields containing detailed information
    pub fields: JiraIssueFields,
}

/// Detailed fields from a Jira issue.
///
/// Contains the descriptive and status information from issues that
/// is relevant for task creation and tracking. This represents a subset
/// of Jira's extensive field system, focusing on essential data.
/// Unknown / custom fields are captured in [`extra`] via serde flatten.
#[derive(Serialize, Deserialize, Debug)]
pub struct JiraIssueFields {
    /// Issue title/summary (required field in Jira)
    pub summary: String,
    /// Detailed description (may be empty or contain rich text)
    #[serde(default)]
    pub description: Option<String>,
    /// Current workflow status information
    pub status: JiraStatus,
    /// Date when the issue was resolved (ISO format if completed)
    #[serde(default)]
    pub resolutiondate: Option<String>,
    /// Issue priority (Highest / High / Medium / …)
    #[serde(default)]
    pub priority: Option<JiraPriority>,
    /// Last update timestamp from Jira (ISO-8601)
    #[serde(default)]
    pub updated: Option<String>,
    /// Custom and other fields keyed by Jira field id (e.g. `customfield_12345`).
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// Jira issue status information.
///
/// Represents the current workflow status of an issue, used for filtering
/// completed vs. in-progress work. Status names vary by Jira configuration
/// and localization settings.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct JiraStatus {
    /// Stable status id from Jira (preferred for storage / joins)
    #[serde(default, deserialize_with = "deserialize_jira_id")]
    pub id: String,
    /// Status name (e.g., "Done", "In Progress", "Решена" for Russian locale)
    pub name: String,
}

/// Accepts Jira ids as JSON string or number (`"3"` / `3`).
fn deserialize_jira_id<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<Value>::deserialize(deserializer)?;
    Ok(match value {
        Some(Value::String(s)) => s,
        Some(Value::Number(n)) => n.to_string(),
        _ => String::new(),
    })
}

/// Jira issue priority.
///
/// Classic Jira uses numeric ids where lower means higher urgency
/// (e.g. `"1"` = Highest). Used for inbox sorting.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct JiraPriority {
    /// Priority display name (e.g. "High", "Highest")
    pub name: String,
    /// Numeric priority id as string (lower = more urgent in classic schemes)
    #[serde(default)]
    pub id: Option<String>,
}

/// Response structure for Jira issue search queries.
///
/// Contains the results of JQL (Jira Query Language) searches,
/// including the matching issues and pagination information.
#[derive(Serialize, Deserialize, Debug)]
pub struct JiraSearchResults {
    /// Index of the first issue in this page
    #[serde(default, rename = "startAt")]
    pub start_at: u32,
    /// Requested page size
    #[serde(default, rename = "maxResults")]
    pub max_results: u32,
    /// Total matching issues across all pages
    #[serde(default)]
    pub total: u32,
    /// Array of issues matching the search criteria
    pub issues: Vec<JiraIssue>,
}

/// Jira API client with session management capabilities.
///
/// This client handles authentication, session caching, and issue retrieval
/// from Jira instances. It implements the [`Session`] trait for automatic
/// credential management and retry logic.
///
/// ## Thread Safety
///
/// The client is not thread-safe due to mutable retry state. Each thread
/// should use its own client instance for concurrent operations.
///
/// ## Session Lifecycle
///
/// 1. **Initialization**: Client created with configuration
/// 2. **Authentication**: Credentials prompted when first needed
/// 3. **Session Caching**: Successful sessions stored for reuse
/// 4. **Automatic Retry**: Expired sessions trigger re-authentication
/// 5. **Error Handling**: Persistent failures return empty results
#[derive(Debug)]
pub struct Jira {
    /// HTTP client for making API requests with connection pooling
    client: Client,
    /// Configuration containing API endpoint and user information
    config: JiraConfig,
    /// In-memory storage for authentication credentials during auth process
    credentials: Option<LoginCredentials>,
    /// Counter for tracking authentication retry attempts
    retries: i32,
}

impl Session for Jira {
    /// Performs session-based authentication with Jira.
    ///
    /// This method implements Jira's session authentication flow using the
    /// REST API. It sends user credentials to the authentication endpoint
    /// and receives a session cookie that can be used for subsequent requests.
    ///
    /// ## Authentication Process
    ///
    /// 1. **Credential Validation**: Ensures credentials are set before proceeding
    /// 2. **HTTP Request**: POST to the session authentication endpoint with JSON credentials
    /// 3. **Response Validation**: Checks for successful HTTP status codes
    /// 4. **Cookie Extraction**: Parses session information from the response
    /// 5. **Format Preparation**: Creates properly formatted cookie string for headers
    ///
    /// ## Session Cookie Format
    ///
    /// The returned session ID is formatted as `{cookie_name}={cookie_value}` and
    /// should be included in the `Cookie` header of subsequent API requests.
    ///
    /// # Returns
    ///
    /// Returns a formatted session cookie string on successful authentication.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No credentials have been set (programming error)
    /// - HTTP request fails due to network issues
    /// - Credentials are invalid (401 response)
    /// - Jira returns an unexpected response format
    /// - Session parsing fails
    async fn login(&self) -> Result<String> {
        // Ensure credentials are available for authentication
        let credentials = self.credentials.clone().expect("Credentials not set!");

        // Build authentication endpoint URL
        let auth_url = format!("{}/{}", self.config.api_url, AUTH_URL);

        // Send authentication request with JSON credentials
        let auth_res = self.client.post(auth_url).json(&credentials).send().await?;

        // Validate response status
        if !auth_res.status().is_success() {
            anyhow::bail!("Jira authenticate failed")
        }

        // Parse session information from response
        let session_res = auth_res.json::<JiraSessionResponse>().await?;

        // Format session cookie for use in subsequent requests
        let session_id = format!("{}={}", session_res.session.name, session_res.session.value);
        Ok(session_id)
    }

    /// Sets user credentials for Jira authentication.
    ///
    /// Stores the provided username and password in memory for use during
    /// the authentication process. This method is called by the session
    /// management system when credentials are needed.
    ///
    /// ## Security Notes
    ///
    /// - Credentials are only stored in memory temporarily
    /// - Password is stored in plain text for authentication
    /// - No persistence to disk or configuration files
    /// - Credentials are cleared after successful authentication
    ///
    /// # Arguments
    ///
    /// * `password` - The user's Jira password in plain text
    ///
    /// # Returns
    ///
    /// Always returns `Ok(())` as this operation cannot fail.
    fn set_credentials(&mut self, password: &str) -> Result<()> {
        self.credentials = Some(LoginCredentials {
            username: self.config.login.to_string(),
            password: password.to_owned(),
        });
        Ok(())
    }

    /// Returns the filename for storing Jira session tokens.
    ///
    /// The session file is stored in the user's application data directory
    /// and contains the cached session token for automatic login restoration.
    fn session_id_file(&self) -> &str {
        SESSION_ID_FILE
    }

    /// Returns a configured Secret instance for secure password prompting.
    ///
    /// The Secret manager handles secure password input with hidden characters
    /// and optional encrypted caching in the user's data directory.
    ///
    /// # Returns
    ///
    /// A configured `Secret` instance with Jira-specific prompts and file names.
    fn secret(&self) -> Secret {
        Secret::new(SECRET_FILE, "Enter your Jira password")
    }

    /// Returns the current authentication retry count.
    ///
    /// Used by the session management system to track failed authentication
    /// attempts and implement retry limits.
    fn retry(&self) -> i32 {
        self.retries
    }

    /// Increments the authentication retry counter.
    ///
    /// Called after each failed authentication attempt to track progress
    /// toward the maximum retry limit defined in the session management system.
    fn inc_retry(&mut self) {
        self.retries += 1;
    }

    /// Resets the authentication retry counter to zero.
    ///
    /// Called after successful authentication to ensure future session
    /// requests start with a clean slate.
    fn reset_retry(&mut self) {
        self.retries = 0;
    }
}

impl Jira {
    /// Creates a new Jira API client instance.
    ///
    /// Initializes the HTTP client with default settings suitable for Jira API
    /// interactions. The client is configured for JSON requests and includes
    /// appropriate timeout and connection settings.
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration containing Jira URL and login information
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use kasl::api::jira::{Jira, JiraConfig};
    ///
    /// let config = JiraConfig {
    ///     login: "username".to_string(),
    ///     api_url: "https://jira.company.com".to_string(),
    ///     completed_statuses: Vec::new(),
    /// };
    /// let jira = Jira::new(&config);
    /// ```
    pub fn new(config: &JiraConfig) -> Self {
        Self {
            client: Client::new(),
            config: config.clone(),
            credentials: None,
            retries: 0,
        }
    }

    /// Retrieves all issues completed by the current user on a specific date.
    ///
    /// This method performs a sophisticated issue search using JQL (Jira Query Language)
    /// to find issues that were marked as completed on the specified date. The search
    /// includes robust error handling and automatic session management with retry logic.
    ///
    /// ## JQL Query Details
    ///
    /// The search uses the following criteria:
    /// - **Resolution Date**: Issues resolved within the full day range (00:00 to 23:59)
    /// - **Assignee Filter**: Only issues assigned to the current user (`currentUser()`)
    ///
    /// ## Session Management
    ///
    /// The method implements sophisticated session handling:
    /// 1. **Session Retrieval**: Get or create a valid session token using the Session trait
    /// 2. **API Request**: Execute the JQL search with session cookie authentication
    /// 3. **Error Handling**: Detect HTTP 401 (Unauthorized) responses indicating expired sessions
    /// 4. **Automatic Retry**: Clear cached session and retry authentication up to the limit
    /// 5. **Graceful Degradation**: Return empty results on persistent authentication failures
    ///
    /// ## Error Recovery Strategy
    ///
    /// Unlike other API integrations, Jira errors are allowed to propagate rather
    /// than returning empty results silently. This is because Jira data is typically more
    /// critical for work tracking, and users should be aware of connection issues.
    ///
    /// However, authentication failures are handled gracefully with automatic
    /// retry logic and eventual fallback to empty results after exhausting retries.
    ///
    /// ## Date Handling
    ///
    /// The method formats the provided date to ensure proper JQL syntax and
    /// covers the entire day from midnight to 23:59 to capture all possible
    /// resolution times within the target date.
    ///
    /// # Arguments
    ///
    /// * `date` - The date to search for completed issues (in any timezone)
    ///
    /// # Returns
    ///
    /// Returns a vector of [`JiraIssue`] objects representing completed work.
    /// Returns an empty vector if:
    /// - No issues are found matching the criteria
    /// - Authentication fails persistently after all retries
    /// - Network errors occur during the request
    ///
    /// # Errors
    ///
    /// May return errors for:
    /// - JSON parsing failures in API responses
    /// - Unexpected HTTP response formats
    /// - Session token formatting errors
    ///
    /// Network errors and authentication failures are handled gracefully
    /// and result in empty results rather than propagated errors.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use kasl::api::jira::{Jira, JiraConfig};
    /// # use chrono::NaiveDate;
    /// # use anyhow::Result;
    /// # async fn example() -> Result<()> {
    /// let config = JiraConfig {
    ///     login: "username".to_string(),
    ///     api_url: "https://jira.company.com".to_string(),
    ///     completed_statuses: Vec::new(),
    /// };
    /// let mut jira = Jira::new(&config);
    ///
    /// let today = chrono::Local::now().date_naive();
    /// let issues = jira.get_completed_issues(&today).await?;
    ///
    /// for issue in issues {
    ///     println!("Completed: {} - {}", issue.key, issue.fields.summary);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_completed_issues(&mut self, date: &NaiveDate) -> Result<Vec<JiraIssue>> {
        let mut local_retries = 0;
        loop {
            let session_id = self.get_session_id().await?;

            match self.fetch_completed_pages(&session_id, date).await {
                Ok(issues) => return Ok(issues),
                Err(SearchPageError::Unauthorized) if local_retries < MAX_RETRY_COUNT => {
                    let _ = self.delete_session_id();
                    local_retries += 1;
                    tokio::time::sleep(Duration::from_secs(1)).await;
                }
                Err(SearchPageError::Unauthorized) => {
                    anyhow::bail!("Jira session unauthorized after retries")
                }
                Err(SearchPageError::Other(msg)) => {
                    anyhow::bail!("Jira completed-issues search failed: {msg}")
                }
            }
        }
    }

    /// Fetches all pages of completed issues for a valid session cookie.
    async fn fetch_completed_pages(&self, session_id: &str, date: &NaiveDate) -> std::result::Result<Vec<JiraIssue>, SearchPageError> {
        // Filter by resolution date only. Do not use `status in (...)` with English
        // defaults like "Done"/"Resolved": on localized Jira those names are invalid
        // and the whole JQL fails (HTTP 400), which used to look like "no issues".
        let date_str = date.format("%Y-%m-%d").to_string();
        let jql = format!(
            "assignee = currentUser() AND resolved >= \"{}\" AND resolved <= \"{} 23:59\"",
            date_str, date_str
        );
        let url = format!("{}/{}", self.config.api_url, SEARCH_URL);

        let mut all = Vec::new();
        let mut start_at: u32 = 0;

        loop {
            let mut headers = HeaderMap::new();
            headers.insert(
                COOKIE,
                HeaderValue::from_str(session_id).map_err(|e| SearchPageError::Other(format!("invalid session cookie: {e}")))?,
            );

            let res = self
                .client
                .get(&url)
                .headers(headers)
                .query(&[
                    ("jql", jql.as_str()),
                    ("fields", "summary,status,priority,updated,resolutiondate"),
                    ("startAt", &start_at.to_string()),
                    ("maxResults", &SEARCH_PAGE_SIZE.to_string()),
                ])
                .send()
                .await
                .map_err(|e| SearchPageError::Other(format!("request failed: {e}")))?;

            match res.status() {
                StatusCode::UNAUTHORIZED => return Err(SearchPageError::Unauthorized),
                status if !status.is_success() => {
                    let body = res.text().await.unwrap_or_default();
                    return Err(SearchPageError::Other(format!("HTTP {status}: {body}")));
                }
                _ => {}
            }

            let page: JiraSearchResults = res.json().await.map_err(|e| SearchPageError::Other(format!("invalid JSON: {e}")))?;
            let batch_len = page.issues.len() as u32;
            all.extend(page.issues);

            start_at += batch_len;
            if batch_len == 0 || start_at >= page.total {
                break;
            }
        }

        Ok(all)
    }

    /// Fetches open issues currently assigned to the authenticated user.
    ///
    /// Uses JQL `assignee = currentUser() AND resolution is EMPTY`. Paginates
    /// through all matching issues (`startAt` / `total`). Extra field ids
    /// (custom fields such as Scoring) are included in the `fields` query.
    ///
    /// Auth failures and network errors return an empty list (same pattern as
    /// [`get_completed_issues`]) so callers can keep polling safely.
    pub async fn get_assigned_open_issues(&mut self, extra_field_ids: &[String]) -> Result<Vec<JiraIssue>> {
        let mut local_retries = 0;
        loop {
            let session_id = match self.get_session_id().await {
                Ok(id) => id,
                Err(_) => return Ok(Vec::new()),
            };

            match self.fetch_assigned_open_pages(&session_id, extra_field_ids).await {
                Ok(issues) => return Ok(issues),
                Err(SearchPageError::Unauthorized) if local_retries < MAX_RETRY_COUNT => {
                    let _ = self.delete_session_id();
                    local_retries += 1;
                    tokio::time::sleep(Duration::from_secs(1)).await;
                }
                Err(_) => return Ok(Vec::new()),
            }
        }
    }

    /// Like [`get_assigned_open_issues`], but never prompts for a password.
    ///
    /// Uses a cached session cookie and/or encrypted `.jira_secret`. Returns
    /// `Ok(None)` when neither is available so background daemons can skip
    /// the poll without blocking on stdin.
    pub async fn get_assigned_open_issues_noninteractive(&mut self, extra_field_ids: &[String]) -> Result<Option<Vec<JiraIssue>>> {
        let mut local_retries = 0;
        loop {
            let Some(session_id) = self.session_id_noninteractive().await? else {
                return Ok(None);
            };

            match self.fetch_assigned_open_pages(&session_id, extra_field_ids).await {
                Ok(issues) => return Ok(Some(issues)),
                Err(SearchPageError::Unauthorized) if local_retries < MAX_RETRY_COUNT => {
                    let _ = self.delete_session_id();
                    local_retries += 1;
                    tokio::time::sleep(Duration::from_secs(1)).await;
                }
                Err(_) => return Ok(Some(Vec::new())),
            }
        }
    }

    /// Fetches all pages of assigned open issues for a valid session cookie.
    async fn fetch_assigned_open_pages(&self, session_id: &str, extra_field_ids: &[String]) -> std::result::Result<Vec<JiraIssue>, SearchPageError> {
        let jql = "assignee = currentUser() AND resolution is EMPTY ORDER BY priority ASC, updated DESC";
        let fields = build_search_fields(extra_field_ids);
        let url = format!("{}/{}", self.config.api_url, SEARCH_URL);

        let mut all = Vec::new();
        let mut start_at: u32 = 0;

        loop {
            let mut headers = HeaderMap::new();
            headers.insert(
                COOKIE,
                HeaderValue::from_str(session_id).map_err(|e| SearchPageError::Other(format!("invalid session cookie: {e}")))?,
            );

            let res = self
                .client
                .get(&url)
                .headers(headers)
                .query(&[
                    ("jql", jql),
                    ("fields", fields.as_str()),
                    ("startAt", &start_at.to_string()),
                    ("maxResults", &SEARCH_PAGE_SIZE.to_string()),
                ])
                .send()
                .await
                .map_err(|e| SearchPageError::Other(format!("request failed: {e}")))?;

            match res.status() {
                StatusCode::UNAUTHORIZED => return Err(SearchPageError::Unauthorized),
                status if !status.is_success() => {
                    let body = res.text().await.unwrap_or_default();
                    return Err(SearchPageError::Other(format!("HTTP {status}: {body}")));
                }
                _ => {}
            }

            let page: JiraSearchResults = res.json().await.map_err(|e| SearchPageError::Other(format!("invalid JSON: {e}")))?;
            let batch_len = page.issues.len() as u32;
            all.extend(page.issues);

            start_at += batch_len;
            if batch_len == 0 || start_at >= page.total {
                break;
            }
        }

        Ok(all)
    }

    /// Resolves a session from cache / secret without prompting.
    async fn session_id_noninteractive(&mut self) -> Result<Option<String>> {
        let session_id_file_path = crate::libs::data_storage::DataStorage::new().get_path(SESSION_ID_FILE)?;
        let path_str = session_id_file_path.to_str().unwrap_or_default();

        if let Ok(session_id) = Self::read_session_id(path_str) {
            return Ok(Some(session_id));
        }

        let Some(password) = self.secret().try_get_cached() else {
            return Ok(None);
        };

        self.set_credentials(&password)?;
        match self.login().await {
            Ok(session_id) => {
                let _ = Self::write_session_id(path_str, &session_id);
                self.reset_retry();
                Ok(Some(session_id))
            }
            Err(_) => Ok(None),
        }
    }

    /// Builds a browse URL for an issue key using this client's API base.
    pub fn issue_browse_url(&self, key: &str) -> String {
        let base = self.config.api_url.trim_end_matches('/');
        format!("{}/browse/{}", base, key)
    }

    /// Maps a Jira priority id to a sortable rank (lower = more urgent).
    pub fn priority_rank(priority: &Option<JiraPriority>) -> i32 {
        priority
            .as_ref()
            .and_then(|p| p.id.as_ref())
            .and_then(|id| id.parse::<i32>().ok())
            .unwrap_or(999)
    }

    /// Extracts a numeric value from a Jira custom-field JSON value.
    ///
    /// Supports bare numbers, numeric strings, and objects with `value` / `amount`.
    pub fn extract_number(value: &Value) -> Option<f64> {
        match value {
            Value::Number(n) => n.as_f64(),
            Value::String(s) => s.trim().parse().ok(),
            Value::Object(map) => map
                .get("value")
                .and_then(Self::extract_number)
                .or_else(|| map.get("amount").and_then(Self::extract_number)),
            _ => None,
        }
    }

    /// Reads a numeric custom field from issue extras by field id.
    pub fn sort_value_from_issue(issue: &JiraIssue, field_id: &str) -> Option<f64> {
        issue.fields.extra.get(field_id).and_then(Self::extract_number)
    }
}

/// Internal error for paginated search (auth vs other failures).
enum SearchPageError {
    Unauthorized,
    Other(String),
}

fn build_search_fields(extra_field_ids: &[String]) -> String {
    let mut fields = vec!["summary".to_string(), "status".to_string(), "priority".to_string(), "updated".to_string()];
    for id in extra_field_ids {
        let trimmed = id.trim();
        if !trimmed.is_empty() && !fields.iter().any(|f| f == trimmed) {
            fields.push(trimmed.to_string());
        }
    }
    fields.join(",")
}

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

    #[test]
    fn extract_number_from_primitives_and_objects() {
        assert_eq!(Jira::extract_number(&json!(12.5)), Some(12.5));
        assert_eq!(Jira::extract_number(&json!("42")), Some(42.0));
        assert_eq!(Jira::extract_number(&json!({"value": 7})), Some(7.0));
        assert_eq!(Jira::extract_number(&json!({"amount": "3.5"})), Some(3.5));
        assert_eq!(Jira::extract_number(&json!(null)), None);
    }

    #[test]
    fn build_search_fields_includes_custom_ids() {
        let fields = build_search_fields(&["customfield_10001".to_string(), "summary".to_string()]);
        assert!(fields.contains("summary"));
        assert!(fields.contains("customfield_10001"));
        assert_eq!(fields.matches("summary").count(), 1);
    }
}

/// Configuration for Jira API integration.
///
/// This structure holds the necessary information for connecting to Jira
/// instances, including both cloud and server/data center deployments.
/// The configuration is designed to be serializable for storage in
/// configuration files.
///
/// ## Security Notes
///
/// - Passwords are never stored in configuration files
/// - Only usernames and API endpoints are persisted
/// - Session tokens are cached separately with encryption
/// - Configuration files should have restricted permissions
///
/// ## Supported Jira Instances
///
/// - **Atlassian Cloud**: Uses `https://company.atlassian.net` format
/// - **Server/Data Center**: Uses custom domain like `https://jira.company.com`
/// - **Local Development**: Can use `http://localhost:8080` for testing
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct JiraConfig {
    /// Jira username for authentication.
    ///
    /// This should be the actual username, not an email address,
    /// unless your Jira instance is configured to use email addresses
    /// as usernames. Check with your Jira administrator if unsure.
    ///
    /// For Atlassian Cloud instances, this is typically the email address
    /// used to register the account.
    pub login: String,

    /// Base URL of the Jira instance.
    ///
    /// Examples:
    /// - Atlassian Cloud: `https://company.atlassian.net`
    /// - Server/Data Center: `https://jira.company.com`
    /// - Local development: `http://localhost:8080`
    ///
    /// Do not include the `/rest/api/` path as it will be added automatically.
    /// The URL should point to the root of your Jira installation.
    pub api_url: String,

    /// Deprecated: previously used in `status in (...)` for completed-issue search.
    ///
    /// Kept for config compatibility. Discovery now filters by `resolved` date only,
    /// because non-existent status names (e.g. English "Done" on a Russian Jira)
    /// make the whole JQL fail.
    #[serde(default = "default_completed_statuses")]
    pub completed_statuses: Vec<String>,
}

/// Empty default — status names are no longer used in completed-issue JQL.
fn default_completed_statuses() -> Vec<String> {
    Vec::new()
}

impl JiraConfig {
    /// Returns the configuration module metadata for Jira.
    ///
    /// Used by the configuration system to identify and manage
    /// Jira-specific settings during interactive setup. This provides
    /// the human-readable name and internal key for the module.
    ///
    /// # Returns
    ///
    /// A `ConfigModule` with Jira identification information.
    pub fn module() -> ConfigModule {
        ConfigModule {
            key: "jira".to_string(),
            name: "Jira".to_string(),
        }
    }

    /// Runs an interactive configuration setup for Jira integration.
    ///
    /// Prompts the user for Jira instance URL and username, using existing
    /// configuration values as defaults if available. This method provides
    /// a user-friendly way to configure Jira integration during initial
    /// setup or reconfiguration.
    ///
    /// ## Interactive Prompts
    ///
    /// 1. **Username**: Prompts for Jira username (or email for cloud instances)
    /// 2. **API URL**: Prompts for Jira instance URL with validation hints
    ///
    /// Both prompts will show existing values as defaults if configuration
    /// already exists, making it easy to update only specific values without
    /// re-entering everything.
    ///
    /// ## Configuration Validation
    ///
    /// While this method doesn't validate the actual connection to Jira,
    /// it provides helpful prompts and examples to guide users toward
    /// correct configuration values.
    ///
    /// # Arguments
    ///
    /// * `config` - Existing Jira configuration to use as defaults (if any)
    ///
    /// # Returns
    ///
    /// * `Result<Self>` - New Jira configuration with user input
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Terminal input/output fails
    /// - User cancels the configuration process
    /// - Input validation fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use kasl::api::JiraConfig;
    /// # use anyhow::Result;
    /// # fn example() -> Result<()> {
    /// let existing_config = Some(JiraConfig {
    ///     login: "olduser".to_string(),
    ///     api_url: "https://old-jira.com".to_string(),
    ///     completed_statuses: Vec::new(),
    /// });
    ///
    /// let new_config = JiraConfig::init(&existing_config)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn init(config: &Option<Self>) -> Result<Self> {
        // Use existing configuration as defaults, or create empty defaults
        let config = config.clone().unwrap_or(Self {
            login: "".to_string(),
            api_url: "".to_string(),
            completed_statuses: default_completed_statuses(),
        });

        // Display configuration module header
        msg_print!(Message::ConfigModuleJira);

        // Interactive configuration with existing values as defaults
        Ok(Self {
            completed_statuses: config.completed_statuses.clone(),
            login: Input::with_theme(&ColorfulTheme::default())
                .with_prompt("Enter your Jira login")
                .default(config.login)
                .interact_text()?,
            api_url: Input::with_theme(&ColorfulTheme::default())
                .with_prompt("Enter the Jira API URL")
                .default(config.api_url)
                .interact_text()?,
        })
    }
}