kasl-cli 1.15.0

Work activity tracker CLI: automatic workday and break detection, task management with Jira/GitLab integration, productivity reports and exports
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
//! Jira client: completed issues for task discovery, assigned open
//! issues for the inbox poller.
//!
//! ```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;

const MAX_RETRY_COUNT: i32 = 3;

const SEARCH_PAGE_SIZE: u32 = 100;

const SESSION_ID_FILE: &str = ".jira_session_id";

const SECRET_FILE: &str = ".jira_secret";

const AUTH_URL: &str = "rest/auth/1/session";

const SEARCH_URL: &str = "rest/api/2/search";

const ISSUE_URL: &str = "rest/api/2/issue";

/// How long one Jira request may take before it is abandoned.
///
/// The watcher drains toast buttons and polls on the same runtime; a request
/// that never answers would hold a pressed button, or every poll after it,
/// forever. Generous, because a page of a hundred issues on a slow Jira is
/// legitimately slow.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// Login pair, held in memory only while authenticating.
#[derive(Serialize, Clone, Debug)]
pub struct LoginCredentials {
    username: String,
    password: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct JiraSessionResponse {
    session: JiraSession,
}

/// Session cookie (typically `JSESSIONID`) sent on every API request.
#[derive(Serialize, Deserialize, Debug)]
struct JiraSession {
    name: String,
    value: String,
}

/// The slice of a Jira issue kasl works with.
#[derive(Serialize, Deserialize, Debug)]
pub struct JiraIssue {
    /// Numeric issue id assigned by Jira.
    pub id: String,
    /// Human-readable key, e.g. "PROJECT-123".
    pub key: String,
    pub fields: JiraIssueFields,
}

/// The fields kasl reads; custom fields land in `extra` via 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>,
}

/// Workflow status; names vary by configuration and locale.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
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,
    /// The fixed category the status belongs to, whatever it is called.
    #[serde(default, rename = "statusCategory", skip_serializing_if = "Option::is_none")]
    pub category: Option<JiraCategory>,
}

impl JiraStatus {
    /// Which of Jira's fixed categories the status is in.
    pub fn category(&self) -> StatusCategory {
        self.category
            .as_ref()
            .map(|c| StatusCategory::from_key(&c.key))
            .unwrap_or(StatusCategory::Unknown)
    }
}

/// A status category as Jira sends it; only the key is stable.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct JiraCategory {
    /// `new`, `indeterminate` or `done` - the same on every Jira, in every language.
    pub key: String,
}

/// Jira's three status categories, which every workflow status maps onto.
///
/// Status names are the workflow's own and come translated ("In Progress",
/// "В работе"); the category keys do not. Anything kasl decides about where an
/// issue stands is decided on these.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatusCategory {
    /// `new`: not started.
    ToDo,
    /// `indeterminate`: in progress.
    InProgress,
    /// `done`: finished, whatever the resolution.
    Done,
    /// A key this version does not know, or none sent.
    Unknown,
}

impl StatusCategory {
    /// Reads a category key as Jira sends it.
    pub fn from_key(key: &str) -> Self {
        match key {
            "new" => StatusCategory::ToDo,
            "indeterminate" => StatusCategory::InProgress,
            "done" => StatusCategory::Done,
            _ => StatusCategory::Unknown,
        }
    }
}

/// One way out of an issue's current status, as Jira offers it.
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct JiraTransition {
    #[serde(deserialize_with = "deserialize_jira_id")]
    pub id: String,
    /// The transition's own name ("Resolve Issue"), which may differ from where it leads.
    pub name: String,
    /// The status the issue lands in.
    pub to: JiraStatus,
    /// Fields on the transition's screen, keyed by field id (`resolution`).
    #[serde(default)]
    pub fields: HashMap<String, JiraTransitionField>,
}

/// A field on a transition's screen.
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct JiraTransitionField {
    #[serde(default)]
    pub required: bool,
    #[serde(default, rename = "allowedValues")]
    pub allowed_values: Vec<JiraNamedValue>,
}

/// An option of a field with a fixed list, such as a resolution.
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct JiraNamedValue {
    #[serde(default, deserialize_with = "deserialize_jira_id")]
    pub id: String,
    #[serde(default)]
    pub name: String,
}

/// Where an issue stands right now.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IssueState {
    pub status: JiraStatus,
    /// The resolution name when the issue is resolved ("Done", "Won't Fix").
    pub resolution: Option<String>,
}

/// Whether a request may prompt for a password to sign in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionMode {
    /// A command on a terminal: a lost session may be renewed by asking.
    Interactive,
    /// The watcher or a toast button: only a cached session or a stored
    /// password, never a prompt nobody would see.
    Unattended,
}

/// 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>,
}

/// One page of a JQL search.
#[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 client with cached-session management via the [`Session`] trait.
#[derive(Debug)]
pub struct Jira {
    client: Client,
    config: JiraConfig,
    /// Held in memory only while authenticating.
    credentials: Option<LoginCredentials>,
    retries: i32,
}

impl Session for Jira {
    /// Logs in and returns the session cookie as `name=value`.
    async fn login(&self) -> Result<String> {
        let credentials = self.credentials.clone().expect("Credentials not set!");

        let auth_url = format!("{}/{}", self.config.api_url, AUTH_URL);
        let auth_res = self.client.post(auth_url).json(&credentials).send().await?;

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

        let session_res = auth_res.json::<JiraSessionResponse>().await?;

        let session_id = format!("{}={}", session_res.session.name, session_res.session.value);
        Ok(session_id)
    }

    fn set_credentials(&mut self, password: &str) -> Result<()> {
        self.credentials = Some(LoginCredentials {
            username: self.config.login.to_string(),
            password: password.to_owned(),
        });
        Ok(())
    }

    fn session_id_file(&self) -> &str {
        SESSION_ID_FILE
    }

    fn secret(&self) -> Secret {
        Secret::new(SECRET_FILE, "Enter your Jira password")
    }

    fn retry(&self) -> i32 {
        self.retries
    }

    fn inc_retry(&mut self) {
        self.retries += 1;
    }

    fn reset_retry(&mut self) {
        self.retries = 0;
    }
}

impl Jira {
    /// Builds a client from the config; no network activity yet.
    ///
    /// ```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 {
        let client = Client::builder()
            .timeout(REQUEST_TIMEOUT)
            .connect_timeout(Duration::from_secs(10))
            .build()
            .unwrap_or_else(|_| Client::new());
        Self {
            client,
            config: config.clone(),
            credentials: None,
            retries: 0,
        }
    }

    /// Fetches the user's issues resolved on `date` (full-day range).
    ///
    /// A 401 drops the cached session and retries up to the limit; other
    /// failures propagate - completed issues feed the report, so a silent
    /// empty result would hide real problems.
    ///
    /// ```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}")))?;

            if session_is_anonymous(res.headers()) {
                return Err(SearchPageError::Unauthorized);
            }
            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.
    ///
    /// A poll that fails is an error, never an empty list. The caller
    /// reconciles the inbox against whatever comes back, so an empty answer
    /// for a dropped VPN would mark every issue gone - and the next good poll
    /// would bring all of them "back", one change toast per issue.
    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 = self.get_session_id().await?;

            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(e) => return Err(e.into_poll_error()),
            }
        }
    }

    /// Like [`get_assigned_open_issues`], but never prompts for a password.
    ///
    /// Uses a cached session cookie and/or the keyring secret. Returns
    /// `Ok(None)` when neither is available so background daemons can skip
    /// the poll without blocking on stdin. A poll that fails is an error, for
    /// the same reason as in [`get_assigned_open_issues`]: the daemon must
    /// skip the reconcile, not reconcile against nothing.
    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(e) => return Err(e.into_poll_error()),
            }
        }
    }

    /// Fetches all pages of assigned open issues for a valid session cookie.
    ///
    /// The order is by key, not by priority or update time: pages are cut by
    /// offset, and an order that an ordinary edit can reshuffle moves issues
    /// across a page boundary while the pages are read - one issue skipped is
    /// one issue marked gone, then toasted "back" a poll later. Key order only
    /// moves when an issue is created or resolved, and that case is caught by
    /// [`check_complete`]. The inbox sorts on its own, so nothing here reads
    /// this order.
    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 key ASC";
        let fields = build_search_fields(extra_field_ids);
        let url = format!("{}/{}", self.config.api_url, SEARCH_URL);

        let mut all: Vec<JiraIssue> = Vec::new();
        let mut start_at: u32 = 0;
        let mut first_total: Option<u32> = None;

        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}")))?;

            if session_is_anonymous(res.headers()) {
                return Err(SearchPageError::Unauthorized);
            }
            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;
            first_total.get_or_insert(page.total);
            all.extend(page.issues);

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

        check_complete(all, first_total.unwrap_or(0))
    }

    /// 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),
        }
    }

    /// A session for `mode`, or an error naming how to get one.
    async fn session(&mut self, mode: SessionMode) -> Result<String> {
        match mode {
            SessionMode::Interactive => self.get_session_id().await,
            SessionMode::Unattended => self
                .session_id_noninteractive()
                .await?
                .ok_or_else(|| anyhow::anyhow!("not signed in to Jira; run `kasl inbox sync` on a terminal to sign in")),
        }
    }

    /// Sends one request with the session cookie, renewing a session Jira no longer honours.
    ///
    /// A session Jira has dropped answers with 401, or - on Server and Data
    /// Center - as the anonymous user (see [`session_is_anonymous`]). Either
    /// way the cached cookie is thrown away and the request goes again with a
    /// fresh login, a bounded number of times. Everything else is the caller's
    /// to read, including errors: what a 404 means depends on the question.
    async fn send(&mut self, mode: SessionMode, build: impl Fn(&Client) -> reqwest::RequestBuilder) -> Result<reqwest::Response> {
        let mut retries = 0;
        loop {
            let session_id = self.session(mode).await?;
            let res = build(&self.client).header(COOKIE, HeaderValue::from_str(&session_id)?).send().await?;
            let rejected = res.status() == StatusCode::UNAUTHORIZED || session_is_anonymous(res.headers());
            if !rejected {
                return Ok(res);
            }
            if retries >= MAX_RETRY_COUNT {
                anyhow::bail!("Jira rejected the session {MAX_RETRY_COUNT} times; run `kasl inbox sync` to sign in again");
            }
            let _ = self.delete_session_id();
            retries += 1;
            tokio::time::sleep(Duration::from_secs(1)).await;
        }
    }

    fn issue_url(&self, key: &str, tail: &str) -> String {
        format!("{}/{}/{}{}", self.config.api_url.trim_end_matches('/'), ISSUE_URL, key, tail)
    }

    /// Where `key` stands: its status with category, and its resolution if any.
    ///
    /// `None` when Jira answers 404 - the issue was deleted, moved out of
    /// reach, or is not visible to this account. All three mean the same to
    /// kasl: there is nothing there to act on.
    pub async fn issue_state(&mut self, key: &str, mode: SessionMode) -> Result<Option<IssueState>> {
        let url = self.issue_url(key, "");
        let res = self.send(mode, |c| c.get(&url).query(&[("fields", "status,resolution")])).await?;
        if res.status() == StatusCode::NOT_FOUND {
            return Ok(None);
        }
        let res = ok_or_jira_error(res, &format!("reading {key}")).await?;

        #[derive(Deserialize)]
        struct Body {
            fields: Fields,
        }
        #[derive(Deserialize)]
        struct Fields {
            status: JiraStatus,
            #[serde(default)]
            resolution: Option<JiraNamedValue>,
        }
        let body: Body = res.json().await?;
        Ok(Some(IssueState {
            status: body.fields.status,
            resolution: body.fields.resolution.map(|r| r.name),
        }))
    }

    /// The transitions Jira offers out of the issue's current status, with their screens' fields.
    pub async fn transitions(&mut self, key: &str, mode: SessionMode) -> Result<Vec<JiraTransition>> {
        let url = self.issue_url(key, "/transitions");
        let res = self.send(mode, |c| c.get(&url).query(&[("expand", "transitions.fields")])).await?;
        let res = ok_or_jira_error(res, &format!("reading the transitions of {key}")).await?;

        #[derive(Deserialize)]
        struct Body {
            #[serde(default)]
            transitions: Vec<JiraTransition>,
        }
        Ok(res.json::<Body>().await?.transitions)
    }

    /// Performs transition `id` on `key`, with a resolution when its screen asks for one.
    pub async fn transition(&mut self, key: &str, id: &str, resolution_id: Option<&str>, mode: SessionMode) -> Result<()> {
        let url = self.issue_url(key, "/transitions");
        let mut body = serde_json::json!({ "transition": { "id": id } });
        if let Some(resolution) = resolution_id {
            body["fields"] = serde_json::json!({ "resolution": { "id": resolution } });
        }
        let res = self.send(mode, |c| c.post(&url).json(&body)).await?;
        ok_or_jira_error(res, &format!("moving {key}")).await?;
        Ok(())
    }

    /// Adds a comment to `key`.
    pub async fn add_comment(&mut self, key: &str, text: &str, mode: SessionMode) -> Result<()> {
        let url = self.issue_url(key, "/comment");
        let body = serde_json::json!({ "body": text });
        let res = self.send(mode, |c| c.post(&url).json(&body)).await?;
        ok_or_jira_error(res, &format!("commenting on {key}")).await?;
        Ok(())
    }

    /// Builds the issue-navigator URL listing the user's open issues.
    ///
    /// Summary toasts point here: they speak for many issues at once, so no
    /// single browse URL fits.
    pub fn open_issues_url(&self) -> String {
        let base = self.config.api_url.trim_end_matches('/');
        format!("{base}/issues/?jql=assignee%20%3D%20currentUser()%20AND%20resolution%20is%20EMPTY")
    }

    /// 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),
}

impl SearchPageError {
    /// Names what went wrong with an inbox poll, and what fixes it.
    fn into_poll_error(self) -> anyhow::Error {
        match self {
            SearchPageError::Unauthorized => {
                anyhow::anyhow!("Jira rejected the session {MAX_RETRY_COUNT} times; run `kasl inbox sync` to sign in again")
            }
            SearchPageError::Other(msg) => anyhow::anyhow!("Jira inbox poll failed: {msg}"),
        }
    }
}

/// Whether Jira answered as nobody: the cookie was sent but the session behind it is gone.
///
/// Jira Server and Data Center do not always answer an expired session with
/// 401. The request goes through as the anonymous user, with 200, and
/// `currentUser()` in the JQL then matches nothing. Read as an answer, that
/// empty page marks the whole inbox gone overnight, and the first poll with
/// a fresh session brings every issue "back". Jira says so in headers:
/// `X-AUSERNAME: anonymous`, and `X-Seraph-LoginReason` when the cookie it
/// was given failed.
fn session_is_anonymous(headers: &HeaderMap) -> bool {
    let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).unwrap_or_default();
    let reason = header("x-seraph-loginreason");
    header("x-ausername").eq_ignore_ascii_case("anonymous") || reason.contains("AUTHENTICATED_FAILED") || reason.contains("AUTHENTICATION_DENIED")
}

/// Passes a successful response through, or turns Jira's refusal into words.
///
/// Jira explains a refused write in `errorMessages` and per-field `errors` -
/// "Resolution is required", "You do not have permission to transition this
/// issue". Those sentences are the useful part; the status code alone tells
/// the person nothing they can act on.
async fn ok_or_jira_error(res: reqwest::Response, what: &str) -> Result<reqwest::Response> {
    let status = res.status();
    if status.is_success() {
        return Ok(res);
    }
    let body = res.text().await.unwrap_or_default();
    anyhow::bail!("Jira refused {what} (HTTP {}): {}", status.as_u16(), jira_error_text(&body))
}

/// The human part of a Jira error body, or the body itself when it has none.
pub fn jira_error_text(body: &str) -> String {
    #[derive(Deserialize, Default)]
    struct ErrorBody {
        #[serde(default, rename = "errorMessages")]
        messages: Vec<String>,
        #[serde(default)]
        errors: HashMap<String, String>,
    }
    let parsed: ErrorBody = serde_json::from_str(body).unwrap_or_default();
    let mut parts = parsed.messages;
    let mut fields: Vec<(String, String)> = parsed.errors.into_iter().collect();
    fields.sort();
    parts.extend(fields.into_iter().map(|(field, message)| format!("{field}: {message}")));
    if parts.is_empty() {
        let trimmed = body.trim();
        return if trimmed.is_empty() {
            "no explanation given".to_string()
        } else {
            trimmed.chars().take(300).collect()
        };
    }
    parts.join("; ")
}

/// Keeps a paged search only if it holds every issue Jira counted.
///
/// Pages are cut by offset, so an issue created or resolved while they are
/// read shifts the rest by one, and one issue falls between two pages. Such
/// a list is short by an issue that is still open, and the sync would mark
/// it gone. A poll is either the whole inbox or not an answer; the next poll
/// a few minutes later reads a list that holds still. More than counted is
/// fine - an issue read twice is still one issue, and a new one is simply
/// early - so duplicates are folded and only a shortfall fails.
fn check_complete(issues: Vec<JiraIssue>, total: u32) -> std::result::Result<Vec<JiraIssue>, SearchPageError> {
    let mut seen = std::collections::HashSet::new();
    let unique: Vec<JiraIssue> = issues.into_iter().filter(|issue| seen.insert(issue.key.clone())).collect();
    if (unique.len() as u64) < u64::from(total) {
        return Err(SearchPageError::Other(format!(
            "the pages held {} of {} issues; the list changed while it was read",
            unique.len(),
            total
        )));
    }
    Ok(unique)
}

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 a_status_is_placed_by_its_category_key_not_its_name() {
        let status: JiraStatus = serde_json::from_value(json!({
            "id": 3, "name": "В работе", "statusCategory": {"id": 4, "key": "indeterminate", "name": "В работе"}
        }))
        .unwrap();
        assert_eq!(status.category(), StatusCategory::InProgress);

        let bare: JiraStatus = serde_json::from_value(json!({"id": "1", "name": "Open"})).unwrap();
        assert_eq!(bare.category(), StatusCategory::Unknown, "no category sent is unknown, not to-do");
    }

    #[test]
    fn a_jira_refusal_reads_as_its_own_sentences() {
        let body = r#"{"errorMessages":["You do not have permission to transition this issue."],"errors":{"resolution":"Resolution is required."}}"#;
        assert_eq!(
            jira_error_text(body),
            "You do not have permission to transition this issue.; resolution: Resolution is required."
        );
        assert_eq!(jira_error_text("<html>Bad gateway</html>"), "<html>Bad gateway</html>");
        assert_eq!(jira_error_text(""), "no explanation given");
    }

    #[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);
    }
}

/// Jira connection settings; passwords are never stored here.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct JiraConfig {
    /// Username (email for Atlassian Cloud accounts).
    pub login: String,

    /// Instance root URL, without the `/rest/api/` path.
    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 {
    /// Module metadata for the setup wizard.
    pub fn module() -> ConfigModule {
        ConfigModule {
            key: "jira".to_string(),
            name: "Jira".to_string(),
        }
    }

    /// Interactive setup; existing values become the prompt defaults.
    ///
    /// ```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()?,
        })
    }
}