use std::process::Command;
use tempfile::TempDir;

#[test]
fn test_git_rewrite_ignore() {
    // 1. Setup git repo
    let temp_dir = TempDir::new().unwrap();
    let temp_path = temp_dir.path();
    
    let run_git = |args: &[&str]| {
        let status = Command::new("git")
            .current_dir(temp_path)
            .args(args)
            .status()
            .expect("Failed to run git");
        assert!(status.success(), "Git command failed: {:?}", args);
    };
    
    run_git(&["init"]);
    // Configure user for commit
    run_git(&["config", "user.name", "Test User"]);
    run_git(&["config", "user.email", "test@example.com"]);
    
    // 2. Create files
    let ignored_file = temp_path.join("ignored.txt");
    let kept_file = temp_path.join("kept.txt");
    std::fs::write(&ignored_file, "ignored content").unwrap();
    std::fs::write(&kept_file, "kept content").unwrap();
    
    // 3. Commit files
    run_git(&["add", "."]);
    run_git(&["commit", "-m", "Initial commit with both files"]);
    
    // 4. Add to gitignore
    let gitignore = temp_path.join(".gitignore");
    std::fs::write(&gitignore, "ignored.txt").unwrap();
    run_git(&["add", ".gitignore"]);
    run_git(&["commit", "-m", "Add gitignore"]);
    
    // Verify file is still in history
    let output = Command::new("git")
        .current_dir(temp_path)
        .args(&["ls-files", "ignored.txt"])
        .output()
        .unwrap();
    assert!(output.status.success());
    assert!(!output.stdout.is_empty(), "ignored.txt should be tracked before rewrite");

    // 5. Run l-tool
    // We need to build the binary or use the library function directly.
    // Using library function is easier for integration test.
    
    // But we need to change current dir to temp_path for the library function to find the repo.
    // The library function sets current dir to git root, so it should handle it if we start inside.
    
    // We can't easily call the async function from sync test without tokio runtime.
    let runtime = tokio::runtime::Runtime::new().unwrap();
    
    runtime.block_on(async {
        // Change to temp dir
        std::env::set_current_dir(temp_path).unwrap();
        
        let args = l_tool::commands::git::commands::RewriteIgnoreArgs {
            yes: true,
        };
        
        l_tool::commands::git::rewrite_ignore::execute(args).await.unwrap();
    });
    
    // 6. Verify results
    // ignored.txt should be gone from history
    let output = Command::new("git")
        .current_dir(temp_path)
        .args(&["log", "--all", "--", "ignored.txt"])
        .output()
        .unwrap();
        
    // If removed from history, log should be empty? 
    // Or at least `git ls-files` should be empty.
    
    let output_ls = Command::new("git")
        .current_dir(temp_path)
        .args(&["ls-files", "ignored.txt"])
        .output()
        .unwrap();
    assert!(output_ls.stdout.is_empty(), "ignored.txt should not be tracked after rewrite");
    
    // Check if file exists on disk? 
    // `git rm --cached` leaves file on disk.
    assert!(ignored_file.exists(), "ignored.txt should still exist on disk");
    
    // kept.txt should still be tracked
    let output_kept = Command::new("git")
        .current_dir(temp_path)
        .args(&["ls-files", "kept.txt"])
        .output()
        .unwrap();
    assert!(!output_kept.stdout.is_empty(), "kept.txt should still be tracked");
}
