tedi 0.16.3

Personal productivity CLI for task tracking, time management, and GitHub issue integration
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
//! Shared test infrastructure for integration tests.
//!
//! Provides `TestContext` - a unified test context that handles:
//! - XDG directory setup with proper environment variables
//! - Running commands against the compiled binary
//! - Mock state management for Github API simulation
//! - Named pipe communication for editor simulation
//!
//! # Example
//!
//! ```ignore
//! let ctx = TestContext::build("");
//!
//! // Or with fixtures:
//! let ctx = TestContext::build(r#"
//!     //- /data/blockers/test.md
//!     - task 1
//! "#);
//!
//! let out = ctx.run(&["blocker", "list"]);
//! assert!(out.status.success());
//! ```

/// Global CLI flags that must appear before the subcommand.
const GLOBAL_FLAGS: &[&str] = &["--offline", "--mock", "-v", "--verbose", "-q", "--quiet"];
/// Environment variable names derived from package name
const ENV_GITHUB_TOKEN: &str = concat!(env!("CARGO_PKG_NAME"), "__GITHUB_TOKEN");
const ENV_MOCK_STATE: &str = concat!(env!("CARGO_PKG_NAME"), "_MOCK_STATE");
const ENV_MOCK_PIPE: &str = concat!(env!("CARGO_PKG_NAME"), "_MOCK_PIPE");

/// Base timestamp: 2001-09-11 12:00:00 UTC (midday).
const BASE_TIMESTAMP_SECS: i64 = 1000209600;
/// 12 hours in seconds - the range for randomization.
const HALF_DAY_SECS: i64 = 12 * 60 * 60;
/// Default owner for test issues without a link
const DEFAULT_OWNER: &str = "owner";
/// Default repo for test issues without a link
const DEFAULT_REPO: &str = "repo";
/// Default issue number for test issues without a link
const DEFAULT_NUMBER: u64 = 1;
const OWNER: &str = "o";
const REPO: &str = "r";
pub const USER: &str = "mock_user";

impl Seed {
	pub fn new(value: i64) -> Self {
		assert!((-100..=100).contains(&value), "seed must be in range -100..=100, got {value}");
		Self(value)
	}
}

impl From<i8> for Seed {
	fn from(value: i8) -> Self {
		Self(value as i64)
	}
}

impl TestContext {
	/// Create a new test context from a fixture string with git initialized.
	///
	/// Files in the fixture should use XDG category prefixes:
	/// - `/data/blockers/test.md` → `XDG_DATA_HOME/todo/blockers/test.md`
	/// - `/cache/current.txt` → `XDG_CACHE_HOME/todo/current.txt`
	/// - `/state/db.json` → `XDG_STATE_HOME/todo/db.json`
	///
	/// # Example
	///
	/// ```ignore
	/// let ctx = TestContext::build_with_preexisting_state_unsafe(r#"
	///     //- /data/blockers/test.md
	///     # Project
	///     - task 1
	/// "#);
	/// ```
	pub fn build() -> Self {
		Self::build_with_preexisting_state_unsafe("")
	}

	/// when using this, it's very easy to mismatch the input from what the latest version of actual Issue parsing/rendering would have had encoded. Prefer using Issue-based methods for setting state, like [local](Self::local), [remote](Self::remote), [context](Self::consensus)
	pub fn build_with_preexisting_state_unsafe(fixture_str: &str) -> Self {
		let fixture = Fixture::parse(fixture_str);
		let xdg = Xdg::new(fixture.write_to_tempdir(), env!("CARGO_PKG_NAME"));

		let mock_state_path = xdg.inner.root.join("mock_state.json");
		let pipe_path = xdg.inner.create_pipe("editor_pipe");

		// Set overrides so all library calls use our temp dir
		tedi::mocks::set_issues_dir(xdg.data_dir().join("issues"));
		tedi::current_user::set(USER.to_string());

		let ctx = Self {
			xdg,
			mock_state_path,
			pipe_path,
			is_virtual_repo: false,
		};
		ctx.init_git();
		ctx
	}

	pub fn virtual_repo(mut self) -> Self {
		self.is_virtual_repo = true;
		self
	}

	/// Run a command with proper XDG environment.
	///
	/// Used in cases where we don't have to simulate additional user input. If you're testing `open` command, you probably want to run it through [open builder](Self::open)
	pub fn run(&self, args: &[&str]) -> RunOutput {
		let mut cmd = Command::new(get_binary_path());
		cmd.args(args);
		cmd.env("__IS_INTEGRATION_TEST", "1");
		cmd.env(ENV_GITHUB_TOKEN, "test_token");
		for (key, value) in self.xdg.env_vars() {
			cmd.env(key, value);
		}
		let output = cmd.output().unwrap();
		RunOutput {
			status: output.status,
			stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
			stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
		}
	}

	/// Create an OpenBuilder for running the `open` command with an Issue reference.
	///
	/// Takes an `&Issue` and uses `IssueIndex::from(issue).to_string()` as the selector
	/// pattern passed to the CLI. This is the correct way to identify issues without
	/// relying on absolute paths.
	pub fn open_issue<'a>(&'a self, issue: &'a Issue) -> OpenBuilder<'a> {
		OpenBuilder {
			ctx: self,
			target: BuilderTarget::Issue(issue),
			extra_args: Vec::new(),
			edit_op: None,
			ghost_edit: false,
		}
	}

	/// Create an OpenBuilder for running the `open` command with a Github URL.
	pub fn open_url(&self, repo_info: tedi::RepoInfo, number: u64) -> OpenBuilder<'_> {
		let url = format!("https://github.com/{}/{}/issues/{number}", repo_info.owner(), repo_info.repo());
		OpenBuilder {
			ctx: self,
			target: BuilderTarget::Url(url),
			extra_args: Vec::new(),
			edit_op: None,
			ghost_edit: false,
		}
	}

	/// Create an OpenBuilder for running the `open --touch` command.
	pub fn open_touch(&self, pattern: &str) -> OpenBuilder<'_> {
		OpenBuilder {
			ctx: self,
			target: BuilderTarget::Touch(pattern.to_string()),
			extra_args: Vec::new(),
			edit_op: None,
			ghost_edit: false,
		}
	}

	/// Set up mock Github to return an issue.
	///
	/// The issue parameter should be a serde_json::Value representing the mock state.
	fn setup_mock_state(&self, state: &serde_json::Value) {
		std::fs::write(&self.mock_state_path, serde_json::to_string_pretty(state).unwrap()).unwrap();
	}

	/// Initialize git in the issues directory.
	pub fn init_git(&self) -> Git {
		let git = Git::init(self.xdg.data_dir().join("issues"));
		// Use diff3 conflict style for consistent snapshots across environments
		git.run(&["config", "merge.conflictStyle", "diff3"]).expect("git config merge.conflictStyle failed");
		git
	}

	/// Set up mock Github API from VirtualIssue. Uses defaults: owner="o", repo="r", user="mock_user".
	/// Handles sub-issues automatically.
	/// Panics if same (owner, repo, number) is submitted twice.
	///
	/// If `seed` is provided, timestamps are generated from it for the mock response.
	pub fn remote(&self, issue: &tedi::VirtualIssue, seed: Option<Seed>) -> Issue {
		let issue = with_timestamps(issue, seed, self.is_virtual_repo);
		let (owner, repo, number) = extract_issue_coords(&issue);

		with_state(self, |state| {
			// add_issue_recursive handles its own dedup tracking in remote_issue_ids
			assert!(
				!state.remote_issue_ids.contains(&(owner.clone(), repo.clone(), number)),
				"remote() called twice for same issue: {owner}/{repo}#{number}"
			);
			add_issue_recursive(state, tedi::RepoInfo::new(&owner, &repo), number, None, &issue, issue.identity.as_linked().map(|m| &m.timestamps));
		});

		self.rebuild_mock_state();
		issue
	}

	/// Write issue to local filesystem (uncommitted). Uses defaults: owner="o", repo="r", user="mock_user".
	///
	/// If `seed` is provided, timestamps are generated from it and written to `.meta.json`.
	pub async fn local(&self, issue: &tedi::VirtualIssue, seed: Option<Seed>) -> Issue {
		let mut issue = with_timestamps(issue, seed, self.is_virtual_repo);
		let (owner, repo, number) = extract_issue_coords(&issue);
		with_state(self, |state| assert!(state.local_issues.insert((owner, repo, number)), "local() called twice for same issue"));
		self.sink_local(&mut issue, seed).await;
		issue
	}

	/// Write issue and commit to git as consensus state. Uses defaults: owner="o", repo="r", user="mock_user".
	/// Panics if same (owner, repo, number) is submitted twice.
	///
	/// If `seed` is provided, timestamps are generated from it and written to `.meta.json`.
	pub async fn consensus(&self, issue: &tedi::VirtualIssue, seed: Option<Seed>) -> Issue {
		let mut issue = with_timestamps(issue, seed, self.is_virtual_repo);
		let (owner, repo, number) = extract_issue_coords(&issue);
		with_state(self, |state| {
			assert!(state.consensus_issues.insert((owner, repo, number)), "consensus() called twice for same issue")
		});
		self.init_git();
		self.sink_local(&mut issue, seed).await;
		<Issue as Sink<Consensus>>::sink(&mut issue, None).await.expect("consensus sink failed");
		issue
	}

	/// Set the issues directory override for `Local::issues_dir()`.
	///
	/// Uses the thread_local mock mechanism to isolate test filesystem state.
	/// This is preferred over `set_xdg_env` as it doesn't modify global process env vars.
	pub(crate) fn set_issues_dir_override(&self) {
		tedi::mocks::set_issues_dir(self.xdg.data_dir().join("issues"));
	}

	async fn sink_local(&self, issue: &mut Issue, seed: Option<Seed>) {
		self.set_issues_dir_override();
		<Issue as Sink<LocalFs>>::sink(issue, None).await.expect("local sink failed");
		if let Some(seed) = seed {
			let (owner, repo, number) = extract_issue_coords(issue);
			let timestamps = timestamps_from_seed(seed);
			let meta = IssueMeta {
				user: Some(USER.to_string()),
				timestamps,
			};
			Local::save_issue_meta(tedi::RepoInfo::new(&owner, &repo), number, &meta).expect("save_issue_meta failed");
		}
	}

	fn rebuild_mock_state(&self) {
		with_state(self, |state| {
			let issues: Vec<serde_json::Value> = state
				.remote_issues
				.iter()
				.map(|i| {
					let mut json = serde_json::json!({
						"owner": i.owner,
						"repo": i.repo,
						"number": i.number,
						"title": i.title,
						"body": i.body,
						"state": i.state,
						"owner_login": i.owner_login
					});
					if let Some(reason) = &i.state_reason {
						json["state_reason"] = serde_json::Value::String(reason.clone());
					}
					if !i.labels.is_empty() {
						json["labels"] = serde_json::json!(i.labels);
					}
					// Add timestamps if provided
					if let Some(ts) = &i.timestamps {
						if let Some(t) = ts.title {
							json["title_timestamp"] = serde_json::Value::String(t.to_string());
						}
						if let Some(t) = ts.description {
							json["description_timestamp"] = serde_json::Value::String(t.to_string());
						}
						if let Some(t) = ts.labels {
							json["labels_timestamp"] = serde_json::Value::String(t.to_string());
						}
						if let Some(t) = ts.state {
							json["state_timestamp"] = serde_json::Value::String(t.to_string());
						}
					}
					json
				})
				.collect();

			// Group sub-issue relations by (owner, repo, parent)
			let mut sub_issues_map: std::collections::HashMap<(String, String, u64), Vec<u64>> = std::collections::HashMap::new();
			for rel in &state.remote_sub_issues {
				sub_issues_map.entry((rel.owner.clone(), rel.repo.clone(), rel.parent)).or_default().push(rel.child);
			}

			let sub_issues: Vec<serde_json::Value> = sub_issues_map
				.into_iter()
				.map(|((owner, repo, parent), children)| {
					serde_json::json!({
						"owner": owner,
						"repo": repo,
						"parent": parent,
						"children": children
					})
				})
				.collect();

			let comments: Vec<serde_json::Value> = state
				.remote_comments
				.iter()
				.map(|c| {
					// Use provided timestamp or default to base timestamp
					let ts = c.timestamp.unwrap_or_else(|| jiff::Timestamp::from_second(BASE_TIMESTAMP_SECS).unwrap());
					serde_json::json!({
						"owner": c.owner,
						"repo": c.repo,
						"issue_number": c.issue_number,
						"comment_id": c.comment_id,
						"body": c.body,
						"owner_login": c.owner_login,
						"created_at": ts.to_string(),
						"updated_at": ts.to_string()
					})
				})
				.collect();

			let mut mock_state = serde_json::json!({ "issues": issues });
			if !sub_issues.is_empty() {
				mock_state["sub_issues"] = serde_json::Value::Array(sub_issues);
			}
			if !comments.is_empty() {
				mock_state["comments"] = serde_json::Value::Array(comments);
			}

			self.setup_mock_state(&mock_state);
		});
	}
}

impl<'a> OpenBuilder<'a> {
	/// Add extra CLI arguments.
	pub fn args(mut self, args: &[&'a str]) -> Self {
		self.extra_args.extend(args);
		self
	}

	/// Edit the file to this issue while "editor is open".
	pub fn edit(mut self, issue: &tedi::VirtualIssue) -> Self {
		self.edit_op = Some(EditOperation::FullIssue(Box::new(issue.clone())));
		self
	}

	/// Skip editor and pretend edit was made. Syncs the issue without user interaction.
	pub fn ghost_edit(mut self) -> Self {
		self.ghost_edit = true;
		self
	}

	/// Pause execution when the virtual file is ready for editing.
	///
	/// Returns `(virtual_file_path, continuation)`. The test can:
	/// 1. Read the virtual file at the returned path
	/// 2. Modify it as needed
	/// 3. Call `.resume()` on the continuation to signal completion and get the result
	pub fn break_to_edit(self) -> (PathBuf, PausedEdit) {
		self.ctx.set_issues_dir_override();

		let (global_args, subcommand_args): (Vec<&str>, Vec<&str>) = self.extra_args.into_iter().partition(|arg| GLOBAL_FLAGS.iter().any(|f| arg.starts_with(f)));

		let mut cmd = Command::new(get_binary_path());
		cmd.arg("--mock");
		cmd.args(&global_args);
		cmd.arg("open");
		cmd.args(&subcommand_args);

		match &self.target {
			BuilderTarget::Issue(issue) => {
				let issue_path = tedi::local::LocalPath::from(*issue)
					.resolve_parent(tedi::local::FsReader)
					.expect("failed to resolve issue parent path")
					.search()
					.expect("failed to find issue file")
					.path();
				cmd.arg(&issue_path);
			}
			BuilderTarget::Url(url) => {
				cmd.arg(url);
			}
			BuilderTarget::Touch(pattern) => {
				cmd.arg("--touch").arg(pattern);
			}
		}

		cmd.env("__IS_INTEGRATION_TEST", "1");
		cmd.env(ENV_GITHUB_TOKEN, "test_token");
		for (key, value) in self.ctx.xdg.env_vars() {
			cmd.env(key, value);
		}
		cmd.env(ENV_MOCK_STATE, &self.ctx.mock_state_path);
		cmd.env(ENV_MOCK_PIPE, &self.ctx.pipe_path);
		cmd.stdout(std::process::Stdio::piped());
		cmd.stderr(std::process::Stdio::piped());

		let mut child = cmd.spawn().unwrap();
		let stdout = child.stdout.take().unwrap();
		let stderr = child.stderr.take().unwrap();
		set_nonblocking(&stdout);
		set_nonblocking(&stderr);

		let pipe_path = self.ctx.pipe_path.clone();
		let virtual_edit_base = self.ctx.xdg.inner.root.clone();

		// Wait for virtual file to appear
		let vpath = loop {
			std::thread::sleep(std::time::Duration::from_millis(50));
			if let Some(vpath) = find_virtual_edit_file(&virtual_edit_base) {
				break vpath;
			}
			if child.try_wait().unwrap().is_some() {
				panic!("Process exited before creating virtual file");
			}
		};

		(vpath, PausedEdit { child, stdout, stderr, pipe_path })
	}

	/// Run the command and return RunOutput.
	pub fn run(self) -> RunOutput {
		self.ctx.set_issues_dir_override();

		// Separate global flags from subcommand flags
		let (global_args, subcommand_args): (Vec<&str>, Vec<&str>) = self.extra_args.into_iter().partition(|arg| GLOBAL_FLAGS.iter().any(|f| arg.starts_with(f)));

		let mut cmd = Command::new(get_binary_path());

		// Global flags come first (before subcommand)
		if self.ghost_edit {
			cmd.arg("--mock=ghost-edit");
		} else {
			cmd.arg("--mock");
		}
		cmd.args(&global_args);

		// Then the subcommand
		cmd.arg("open");

		// Then subcommand-specific flags
		cmd.args(&subcommand_args);

		// Then the target
		match &self.target {
			BuilderTarget::Issue(issue) => {
				let issue_path = tedi::local::LocalPath::from(*issue)
					.resolve_parent(tedi::local::FsReader)
					.expect("failed to resolve issue parent path")
					.search()
					.expect("failed to find issue file")
					.path();
				cmd.arg(&issue_path);
			}
			BuilderTarget::Url(url) => {
				cmd.arg(url);
			}
			BuilderTarget::Touch(pattern) => {
				cmd.arg("--touch").arg(pattern);
			}
		}

		cmd.env("__IS_INTEGRATION_TEST", "1");
		cmd.env(ENV_GITHUB_TOKEN, "test_token");
		for (key, value) in self.ctx.xdg.env_vars() {
			cmd.env(key, value);
		}
		cmd.env(ENV_MOCK_STATE, &self.ctx.mock_state_path);
		cmd.env(ENV_MOCK_PIPE, &self.ctx.pipe_path);
		cmd.stdout(std::process::Stdio::piped());
		cmd.stderr(std::process::Stdio::piped());

		let mut child = cmd.spawn().unwrap();

		// Take ownership of stdout/stderr to drain them and prevent pipe buffer deadlock
		let mut stdout = child.stdout.take().unwrap();
		let mut stderr = child.stderr.take().unwrap();
		set_nonblocking(&stdout);
		set_nonblocking(&stderr);
		let mut stdout_buf = Vec::new();
		let mut stderr_buf = Vec::new();

		// Poll for process completion, signaling pipe when it's waiting
		let pipe_path = self.ctx.pipe_path.clone();
		let is_virtual = self.ctx.is_virtual_repo;
		let edit_op = self.edit_op.clone();
		let mut signaled = false;

		while child.try_wait().unwrap().is_none() {
			// Drain pipes to prevent deadlock from full pipe buffers
			drain_pipe(&mut stdout, &mut stdout_buf);
			drain_pipe(&mut stderr, &mut stderr_buf);

			// Process still running
			if !signaled {
				// Give process time to reach pipe wait
				std::thread::sleep(std::time::Duration::from_millis(100));

				// Edit the file while "editor is open" if requested
				if let Some(EditOperation::FullIssue(virtual_issue)) = &edit_op {
					let issue = with_timestamps(virtual_issue, None, is_virtual);
					let vpath = tedi::local::Local::virtual_edit_path(&issue);
					let content = issue.serialize_virtual();
					eprintln!("[test:OpenBuilder] submitting user input // writing to {vpath:?}:\n{content}");
					std::fs::write(&vpath, &content).unwrap();
				}

				// Try to signal the pipe (use nix O_NONBLOCK to avoid blocking)
				// Only mark as signaled if we successfully wrote to the pipe.
				// The pipe open will fail if no reader is waiting yet.
				#[cfg(unix)]
				{
					use std::os::unix::fs::OpenOptionsExt;
					if let Ok(mut pipe) = std::fs::OpenOptions::new().write(true).custom_flags(0x800).open(&pipe_path)
						&& pipe.write_all(b"x").is_ok()
					{
						signaled = true;
					}
				}
			}
			std::thread::sleep(std::time::Duration::from_millis(10));
		}

		// Final drain after process exits
		drain_pipe(&mut stdout, &mut stdout_buf);
		drain_pipe(&mut stderr, &mut stderr_buf);

		child.wait().unwrap();
		RunOutput {
			status: child.try_wait().unwrap().unwrap(),
			stdout: String::from_utf8_lossy(&stdout_buf).into_owned(),
			stderr: String::from_utf8_lossy(&stderr_buf).into_owned(),
		}
	}
}

impl PausedEdit {
	/// Resume execution after modifying the virtual file.
	pub fn resume(mut self) -> RunOutput {
		let mut stdout_buf = Vec::new();
		let mut stderr_buf = Vec::new();

		#[cfg(unix)]
		{
			use std::os::unix::fs::OpenOptionsExt;
			let mut pipe = std::fs::OpenOptions::new()
				.write(true)
				.custom_flags(0x800) // O_NONBLOCK
				.open(&self.pipe_path)
				.expect("failed to open pipe");
			pipe.write_all(b"x").expect("failed to signal pipe");
		}

		while self.child.try_wait().unwrap().is_none() {
			drain_pipe(&mut self.stdout, &mut stdout_buf);
			drain_pipe(&mut self.stderr, &mut stderr_buf);
			std::thread::sleep(std::time::Duration::from_millis(10));
		}

		drain_pipe(&mut self.stdout, &mut stdout_buf);
		drain_pipe(&mut self.stderr, &mut stderr_buf);

		self.child.wait().unwrap();
		RunOutput {
			status: self.child.try_wait().unwrap().unwrap(),
			stdout: String::from_utf8_lossy(&stdout_buf).into_owned(),
			stderr: String::from_utf8_lossy(&stderr_buf).into_owned(),
		}
	}
}

/// Unsafe filesystem operations for tests that genuinely need path-based access.
///
/// **DO NOT USE** unless you are testing filesystem edge cases specifically.
/// Normal tests should use `ctx.open_issue(&issue)` with the proper `Issue` type.
///
/// To use: `use crate::common::are_you_sure::UnsafePathExt;`
pub mod are_you_sure {
	use std::path::{Path, PathBuf};

	use tedi::local::{FsReader, LocalPath};

	use super::TestContext;

	/// Extension trait for unsafe path-based operations.
	///
	/// These methods bypass the proper IssueIndex-based addressing and work
	/// directly with filesystem paths. Only use for tests that specifically
	/// need to verify filesystem behavior or edge cases.
	pub trait UnsafePathExt {
		/// Get the flat format path for an issue: `{number}_-_{title}.md`
		///
		/// **Unsafe**: bypasses proper issue addressing. Use only for filesystem tests.
		fn flat_issue_path(&self, repo_info: tedi::RepoInfo, number: u64, title: &str) -> PathBuf;

		/// Get the directory format path for an issue: `{number}_-_{title}/__main__.md`
		///
		/// **Unsafe**: bypasses proper issue addressing. Use only for filesystem tests.
		fn dir_issue_path(&self, repo_info: tedi::RepoInfo, number: u64, title: &str) -> PathBuf;

		/// Resolve an issue's actual filesystem path after it's been written.
		///
		/// **Unsafe**: uses filesystem search. Prefer working with Issue directly.
		fn resolve_issue_path(&self, issue: &tedi::Issue) -> PathBuf;
	}

	impl UnsafePathExt for TestContext {
		fn flat_issue_path(&self, repo_info: tedi::RepoInfo, number: u64, title: &str) -> PathBuf {
			let sanitized = title.replace(' ', "_");
			self.xdg.data_dir().join(format!("issues/{}/{}/{number}_-_{sanitized}.md", repo_info.owner(), repo_info.repo()))
		}

		fn dir_issue_path(&self, repo_info: tedi::RepoInfo, number: u64, title: &str) -> PathBuf {
			let sanitized = title.replace(' ', "_");
			self.xdg
				.data_dir()
				.join(format!("issues/{}/{}/{number}_-_{sanitized}/__main__.md", repo_info.owner(), repo_info.repo()))
		}

		fn resolve_issue_path(&self, issue: &tedi::Issue) -> PathBuf {
			self.set_issues_dir_override();
			LocalPath::from(issue).resolve_parent(FsReader).unwrap().search().unwrap().path()
		}
	}

	/// Read an issue file's contents directly from the filesystem.
	///
	/// **Unsafe**: bypasses proper issue loading. Use only for filesystem verification tests.
	pub fn read_issue_file(path: &Path) -> String {
		std::fs::read_to_string(path).expect("failed to read issue file")
	}

	/// Write content directly to a filesystem path.
	///
	/// **Unsafe**: bypasses virtual edit path. Use only for tests checking filesystem edge cases.
	pub fn write_to_path(path: &Path, content: &str) {
		if let Some(parent) = path.parent() {
			std::fs::create_dir_all(parent).expect("failed to create parent dirs");
		}
		std::fs::write(path, content).expect("failed to write file");
	}
}
mod snapshot;
use std::{
	cell::RefCell,
	collections::HashSet,
	io::{Read, Write},
	os::fd::AsRawFd,
	path::{Path, PathBuf},
	process::{Command, ExitStatus},
};

pub use snapshot::FixtureIssuesExt;
use tedi::{
	Issue, IssueTimestamps,
	local::{Consensus, IssueMeta, Local, LocalFs},
	sink::Sink,
};
use v_fixtures::{
	Fixture, FixtureRenderer,
	fs_standards::{git::Git, xdg::Xdg},
};

/// Set timestamps on an issue and all its children.
pub fn set_timestamps(issue: &mut Issue, seed: Seed) {
	let timestamps = timestamps_from_seed(seed);
	for (_, node) in issue.iter_mut() {
		node.identity.mut_linked_issue_meta().unwrap().timestamps = timestamps.clone();
	}
}

/// Generate timestamps from a seed value.
///
/// Seed must be in range -100..=100. Each timestamp field gets:
/// 1. A pseudo-random offset in ±12h range (deterministic per seed+index)
/// 2. A deterministic offset based on seed: -100 → -12h, 0 → 0, +100 → +12h
///
/// This means same seed produces same timestamps, but different fields have different
/// random-looking values. Higher seed = newer timestamps = wins in merge conflicts.
///
/// Index mapping for fields:
/// - title: -2
/// - description: -1
/// - labels: 0
/// - comments: 1 (aggregate timestamp for "most recent comment")
pub fn timestamps_from_seed(seed: Seed) -> IssueTimestamps {
	IssueTimestamps {
		title: Some(timestamp_for_field(seed, -2)),
		description: Some(timestamp_for_field(seed, -1)),
		labels: Some(timestamp_for_field(seed, 0)),
		state: Some(timestamp_for_field(seed, 1)),
		comments: vec![],
	}
}

/// Handle for a paused edit operation. Call `.resume()` to continue execution.
pub struct PausedEdit {
	child: std::process::Child,
	stdout: std::process::ChildStdout,
	stderr: std::process::ChildStderr,
	pipe_path: PathBuf,
}

/// Output from running a command.
pub struct RunOutput {
	pub status: ExitStatus,
	pub stdout: String,
	pub stderr: String,
}

/// Render a fixture with optional error output if the command failed.
pub fn render_fixture(renderer: FixtureRenderer<'_>, output: &RunOutput) -> String {
	let result = renderer.always_show_filepath().render();

	// will only see it if snapshot failed. //Q: how much overhead this has though?
	let s = format!("\n\nBINARY FAILED\nstatus: {}\nstdout:\n{}\nstderr:\n{}", output.status, output.stdout, output.stderr);
	eprintln!("{s}");

	result
}

pub fn parse_virtual(content: &str) -> tedi::VirtualIssue {
	tedi::VirtualIssue::parse(content, PathBuf::from("test.md")).expect("failed to parse test issue")
}

/// Builder for running the `open` command with various options.
pub struct OpenBuilder<'a> {
	ctx: &'a TestContext,
	target: BuilderTarget<'a>,
	extra_args: Vec<&'a str>,
	edit_op: Option<EditOperation>,
	ghost_edit: bool,
}

/// Unified test context for integration tests.
///
/// Combines functionality from the old `TodoTestContext` and `SyncTestContext`.
/// Handles XDG directory setup, command execution, and optional mock state.
pub struct TestContext {
	/// The Xdg wrapper managing temp directories
	pub xdg: Xdg,
	/// Path to mock Github state file (for sync tests)
	pub mock_state_path: PathBuf,
	/// Path to named pipe for editor simulation (for sync tests)
	pub pipe_path: PathBuf,
	/// encodes whether the repo associated with test context is virtual.
	//DEPENDS: on us hardcoding `repo` across the board. If that's not a case, then having two issue at different repos where only one is virtual is possible. But with current arch it's always the same repo, so can't have two ways about it.
	pub(crate) is_virtual_repo: bool,
}

/// Seed for deterministic timestamp generation. Must be in range -100..=100.
#[derive(Clone, Copy, Debug, derive_more::Deref, derive_more::DerefMut, derive_more::Display, Eq, derive_more::Into, PartialEq)]
pub struct Seed(i64);

/// What target the OpenBuilder opens.
enum BuilderTarget<'a> {
	/// Open by issue reference (derives path from issue)
	Issue(&'a Issue),
	/// Open by Github URL
	Url(String),
	/// Open by touch pattern (--touch flag)
	Touch(String),
}

/// Set a file descriptor to non-blocking mode.
pub(crate) fn set_nonblocking<F: AsRawFd>(f: &F) {
	//SAFETY: don't care if log is overwritten
	unsafe {
		let fd = f.as_raw_fd();
		let flags = libc::fcntl(fd, libc::F_GETFL);
		libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
	}
}

/// Drain available data from a non-blocking pipe into a buffer.
pub(crate) fn drain_pipe<R: Read>(pipe: &mut R, buf: &mut Vec<u8>) {
	let mut tmp = [0u8; 4096];
	//LOOP: we're just draining, so if fs is functioning, we will see the `Ok(0)`
	loop {
		match pipe.read(&mut tmp) {
			Ok(0) => break,
			Ok(n) => buf.extend_from_slice(&tmp[..n]),
			Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
			Err(e) => panic!("pipe read error: {e}"),
		}
	}
}

pub(crate) fn get_binary_path() -> PathBuf {
	let mut path = std::env::current_exe().unwrap();
	path.pop(); // Remove test binary name
	path.pop(); // Remove 'deps'
	path.push(env!("CARGO_PKG_NAME"));
	path
}

/// Type of edit operation for the builder.
#[derive(Clone)]
enum EditOperation {
	/// Edit using a full VirtualIssue (converted to Issue at run time, writes serialize_virtual)
	FullIssue(Box<tedi::VirtualIssue>),
}

/// Find the most recently modified .md file under the virtual edit base path.
fn find_virtual_edit_file(base: &Path) -> Option<PathBuf> {
	if !base.exists() {
		return None;
	}

	let mut best: Option<(PathBuf, std::time::SystemTime)> = None;

	fn walk(dir: &Path, best: &mut Option<(PathBuf, std::time::SystemTime)>) {
		if let Ok(entries) = std::fs::read_dir(dir) {
			for entry in entries.flatten() {
				let path = entry.path();
				if path.is_dir() {
					walk(&path, best);
				} else if path.extension().is_some_and(|e| e == "md")
					&& let Ok(meta) = path.metadata()
					&& let Ok(mtime) = meta.modified()
					&& best.as_ref().map(|(_, t)| mtime > *t).unwrap_or(true)
				{
					*best = Some((path, mtime));
				}
			}
		}
	}

	walk(base, &mut best);
	best.map(|(p, _)| p)
}

// --- Git/issue setup helpers (formerly in git.rs) ---

/// Convert VirtualIssue to Issue by building HollowIssue with timestamps from seed.
/// Uses defaults: owner="o", repo="r", user="mock_user".
pub(crate) fn with_timestamps(virtual_issue: &tedi::VirtualIssue, seed: Option<Seed>, is_virtual: bool) -> Issue {
	let timestamps = seed.map(timestamps_from_seed).unwrap_or_default();
	let hollow = build_hollow_from_virtual(virtual_issue, &timestamps);
	let parent_idx = tedi::IssueIndex::repo_only((OWNER, REPO).into());
	Issue::from_combined(hollow, virtual_issue.clone(), parent_idx, is_virtual).expect("test hollow must match virtual")
}

/// Generate a timestamp for a specific field index.
///
/// Combines pseudo-random scatter (from seed+index) with deterministic offset (from seed).
fn timestamp_for_field(seed: Seed, field_index: i64) -> jiff::Timestamp {
	// Pseudo-random scatter: hash seed+index to get a value in ±12h range
	let random_offset = pseudo_random_offset(seed, field_index);

	// Deterministic offset: seed maps linearly to ±12h
	// -100 → -12h, 0 → 0, +100 → +12h
	let deterministic_offset = (*seed * HALF_DAY_SECS) / 100;

	let total_offset = random_offset + deterministic_offset;
	jiff::Timestamp::from_second(BASE_TIMESTAMP_SECS + total_offset).expect("valid timestamp")
}

/// Simple pseudo-random number generator seeded by seed+index.
/// Returns a value in range [-HALF_DAY_SECS, +HALF_DAY_SECS].
fn pseudo_random_offset(seed: Seed, index: i64) -> i64 {
	// Combine seed and index into a single value, then hash it
	let combined = (*seed as u64).wrapping_mul(31).wrapping_add(index as u64);
	// Simple xorshift-style mixing
	let mut x = combined;
	x ^= x << 13;
	x ^= x >> 7;
	x ^= x << 17;
	// Map to [-HALF_DAY_SECS, +HALF_DAY_SECS]
	let normalized = (x % (2 * HALF_DAY_SECS as u64 + 1)) as i64;
	normalized - HALF_DAY_SECS
}

thread_local! {
	static GIT_STATE: RefCell<std::collections::HashMap<usize, GitState>> = RefCell::new(std::collections::HashMap::new());
}

fn get_ctx_id(ctx: &TestContext) -> usize {
	ctx as *const TestContext as usize
}

fn with_state<F, R>(ctx: &TestContext, f: F) -> R
where
	F: FnOnce(&mut GitState) -> R, {
	GIT_STATE.with(|state| {
		let mut map = state.borrow_mut();
		let id = get_ctx_id(ctx);
		let entry = map.entry(id).or_default();
		f(entry)
	})
}

/// Recursively build HollowIssue tree from VirtualIssue, setting up remote with timestamps.
fn build_hollow_from_virtual(virtual_issue: &tedi::VirtualIssue, timestamps: &IssueTimestamps) -> tedi::HollowIssue {
	let remote = match &virtual_issue.selector {
		tedi::IssueSelector::GitId(n) => {
			let link = tedi::IssueLink::parse(&format!("https://github.com/{OWNER}/{REPO}/issues/{n}")).unwrap();
			Some(Box::new(tedi::LinkedIssueMeta::new(Some(USER.to_string()), link, timestamps.clone())))
		}
		tedi::IssueSelector::Title(_) | tedi::IssueSelector::Regex(_) => None,
	};

	let children = virtual_issue
		.children
		.iter()
		.map(|(selector, child)| {
			let child_hollow = build_hollow_from_virtual(child, timestamps);
			(*selector, child_hollow)
		})
		.collect();

	tedi::HollowIssue::new(remote, children)
}

/// Extract owner, repo, number from an Issue's identity, with defaults.
/// Uses `issue.identity.link()` from the library, with test-specific fallback defaults
/// for unlinked issues (owner="owner", repo="repo", number=1).
fn extract_issue_coords(issue: &Issue) -> (String, String, u64) {
	if let Some(link) = issue.identity.link() {
		(link.owner().to_string(), link.repo().to_string(), link.number())
	} else {
		(DEFAULT_OWNER.to_string(), DEFAULT_REPO.to_string(), DEFAULT_NUMBER)
	}
}

/// Recursively add an issue and all its children to the mock state.
/// Transforms library `Issue` types into mock JSON state for the test mock server.
fn add_issue_recursive(state: &mut GitState, repo_info: tedi::RepoInfo, number: u64, parent_number: Option<u64>, issue: &Issue, timestamps: Option<&IssueTimestamps>) {
	let owner = repo_info.owner();
	let repo = repo_info.repo();
	let key = (owner.to_string(), repo.to_string(), number);

	if state.remote_issue_ids.contains(&key) {
		panic!("remote() would add duplicate issue: {owner}/{repo}#{number}");
	}
	state.remote_issue_ids.insert(key);

	// Add the issue itself
	let issue_owner_login = issue.user().expect("issue identity must have user - use @user format in test fixtures").to_string();
	state.remote_issues.push(MockIssue {
		owner: owner.to_string(),
		repo: repo.to_string(),
		number,
		title: issue.contents.title.clone(),
		body: issue.body().into(),
		state: issue.contents.state.to_github_state().to_string(),
		state_reason: issue.contents.state.to_github_state_reason().map(|s| s.to_string()),
		labels: issue.contents.labels.clone(),
		owner_login: issue_owner_login,
		timestamps: timestamps.cloned(),
	});

	// Add sub-issue relation if this is a child
	if let Some(parent) = parent_number {
		state.remote_sub_issues.push(SubIssueRelation {
			owner: owner.to_string(),
			repo: repo.to_string(),
			parent,
			child: number,
		});
	}

	// Extract comments (skip first which is the body)
	// Use the per-comment timestamps from IssueTimestamps if available
	let comment_timestamps = timestamps.map(|ts| &ts.comments);
	for (i, comment) in issue.contents.comments.iter().skip(1).enumerate() {
		if let Some(id) = comment.id() {
			let comment_owner_login = comment.user().expect("comment identity must have user - use @user format in test fixtures").to_string();
			let comment_ts = comment_timestamps.and_then(|ts| ts.get(i).copied());
			state.remote_comments.push(MockComment {
				owner: owner.to_string(),
				repo: repo.to_string(),
				issue_number: number,
				comment_id: id,
				body: comment.body.to_string(),
				owner_login: comment_owner_login,
				timestamp: comment_ts,
			});
		}
	}

	// Recursively add children (they inherit the same timestamps)
	for child in issue.children.values() {
		let child_number = child.git_id().expect("child issue must have number for remote mock state");
		add_issue_recursive(state, repo_info, child_number, Some(number), child, timestamps);
	}
}

/// State tracking for additive operations
#[derive(Default)]
struct GitState {
	/// Track which (owner, repo, number) have been used for local files
	local_issues: HashSet<(String, String, u64)>,
	/// Track which (owner, repo, number) have been used for consensus commits
	consensus_issues: HashSet<(String, String, u64)>,
	/// Accumulated mock remote state
	remote_issues: Vec<MockIssue>,
	remote_sub_issues: Vec<SubIssueRelation>,
	remote_comments: Vec<MockComment>,
	/// Track which (owner, repo, number) have been added to remote
	remote_issue_ids: HashSet<(String, String, u64)>,
}

/// Intermediate type for building mock JSON state. Stores owner/repo per-entry
/// because the mock JSON format requires them (unlike library types where they're implicit).
struct MockIssue {
	owner: String,
	repo: String,
	number: u64,
	title: String,
	body: String,
	state: String,
	state_reason: Option<String>,
	labels: Vec<String>,
	owner_login: String,
	/// Timestamps for this issue (if provided via seed)
	timestamps: Option<IssueTimestamps>,
}

/// Intermediate type for building mock JSON state. Stores owner/repo/issue_number per-entry
/// because the mock JSON format requires them (unlike library types where they're implicit).
struct MockComment {
	owner: String,
	repo: String,
	issue_number: u64,
	comment_id: u64,
	body: String,
	owner_login: String,
	/// Timestamp for this comment (if provided via seed)
	timestamp: Option<jiff::Timestamp>,
}

struct SubIssueRelation {
	owner: String,
	repo: String,
	parent: u64,
	child: u64,
}