audb-cli 0.1.11

Command-line interface for AuDB database application framework
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
//! Docker deployment implementation using bollard API

use crate::commands::deploy::config::{DeploymentConfig, DeploymentTarget};
use crate::commands::deploy::state::DeploymentState;
use crate::commands::deploy::templates;
use anyhow::{Context, Result, anyhow};
use bollard::API_DEFAULT_VERSION;
use bollard::Docker;
use bollard::container::LogOutput;
use bollard::models::{ContainerCreateBody, ContainerStateStatusEnum, HostConfig, PortBinding};
use futures_util::stream::StreamExt;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Deploy the project to Docker
pub async fn deploy(
    project_root: &Path,
    config: &DeploymentConfig,
    force_rebuild: bool,
) -> Result<DeploymentState> {
    println!("Starting Docker deployment...");

    // Validate target
    if config.target != DeploymentTarget::Docker {
        return Err(anyhow!("Invalid deployment target for Docker"));
    }

    // Extract deployment parameters
    let project_name = project_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("audb-app");
    let image_name = format!("{}:latest", project_name);
    let container_name = format!("{}-container", project_name);
    let port = config.port.unwrap_or(8080);

    // Detect if this is a workspace member
    let workspace_root = find_workspace_root(project_root)?;
    let is_workspace_member = workspace_root != project_root;

    if is_workspace_member {
        println!("Detected workspace project - will copy entire workspace for Docker build");
    }

    // Connect to Docker daemon
    let docker = Docker::connect_with_local_defaults()
        .context("Failed to connect to Docker daemon. Is Docker running?")?;

    // Verify Docker is accessible
    docker
        .ping()
        .await
        .context("Docker daemon is not responding")?;

    println!("Connected to Docker daemon");

    // Step 1: Build release binary
    println!("Building release binary...");
    build_release_binary(project_root)?;

    // Step 2: Generate Dockerfile if needed (skip for workspace members)
    if !is_workspace_member {
        let dockerfile_path = project_root.join("Dockerfile");
        if force_rebuild || !dockerfile_path.exists() {
            println!("Generating Dockerfile...");
            let dockerfile_content = templates::generate_dockerfile(project_name, config);
            fs::write(&dockerfile_path, dockerfile_content)
                .context("Failed to write Dockerfile")?;
            println!("Dockerfile created at {}", dockerfile_path.display());
        }

        // Generate .dockerignore
        let dockerignore_path = project_root.join(".dockerignore");
        if !dockerignore_path.exists() {
            let dockerignore_content = templates::generate_dockerignore();
            fs::write(&dockerignore_path, dockerignore_content)
                .context("Failed to write .dockerignore")?;
        }
    }

    // Step 3: Build Docker image
    println!("Building Docker image '{}'...", image_name);
    if is_workspace_member {
        build_docker_image_workspace(&docker, project_root, &workspace_root, &image_name).await?;
    } else {
        build_docker_image(&docker, project_root, &image_name).await?;
    }

    // Step 4: Stop existing container if running
    if let Ok(existing_state) = DeploymentState::load(project_root) {
        // Check if it's a Docker deployment and try to stop it
        if existing_state.target == DeploymentTarget::Docker {
            println!(
                "Stopping existing container '{}'...",
                existing_state.service_label
            );
            let _ = stop_container_by_id(&docker, &existing_state.service_label).await;
        }
    }

    // Step 5: Create and start container
    println!("Creating container '{}'...", container_name);
    let container_id = create_container(
        &docker,
        &image_name,
        &container_name,
        port,
        &config.environment,
        &config.volumes,
    )
    .await?;

    println!("Starting container '{}'...", container_id);
    start_container(&docker, &container_id).await?;

    // Step 6: Health check (if configured)
    if let Some(health_check) = &config.healthcheck {
        println!("Waiting for health check...");
        perform_health_check(health_check, port).await?;
        println!("Health check passed");
    }

    // Step 7: Create deployment state
    let state = DeploymentState {
        target: config.target,
        deployed_at: chrono::Utc::now(),
        service_label: container_id.clone(),
        project_name: project_name.to_string(),
    };

    // Save state
    state.save(project_root)?;

    println!("\nDeployment successful!");
    println!("Container ID: {}", container_id);
    println!("Container name: {}", container_name);
    println!("Port: {}", port);
    println!("\nView logs with: au deploy logs");
    println!("Stop with: au deploy stop");

    Ok(state)
}

/// Build release binary using cargo with cross-compilation support
fn build_release_binary(project_root: &Path) -> Result<()> {
    // Detect if we're on macOS and need to cross-compile for Linux
    let target = if cfg!(target_os = "macos") {
        // Detect host architecture - Apple Silicon uses aarch64
        if cfg!(target_arch = "aarch64") {
            Some("aarch64-unknown-linux-gnu")
        } else {
            Some("x86_64-unknown-linux-gnu")
        }
    } else {
        None
    };

    // Check if cross-compilation is needed
    if let Some(target_triple) = target {
        let arch = if target_triple.starts_with("aarch64") {
            "ARM64"
        } else {
            "x86_64"
        };
        println!("Detected macOS - cross-compiling for Linux ({})...", arch);

        // Check if 'cross' is installed
        let cross_check = Command::new("cross").arg("--version").output();

        let use_cross = cross_check.is_ok();

        if use_cross {
            println!("Using 'cross' for cross-compilation...");
            // Build with cross (uses Docker internally)
            // Set environment variables to use vendored OpenSSL for cross-compilation
            let status = Command::new("cross")
                .arg("build")
                .arg("--release")
                .arg("--target")
                .arg(target_triple)
                .env("OPENSSL_STATIC", "1")
                .env("OPENSSL_VENDORED", "1")
                .current_dir(project_root)
                .status()
                .context("Failed to run cross build")?;

            if !status.success() {
                return Err(anyhow!("Cross build failed"));
            }
        } else {
            println!("'cross' not found. Install it with: cargo install cross");
            println!("Attempting native cargo build with target...");

            // Fallback to cargo (may require toolchain)
            let status = Command::new("cargo")
                .arg("build")
                .arg("--release")
                .arg("--target")
                .arg(target_triple)
                .current_dir(project_root)
                .status()
                .context("Failed to run cargo build")?;

            if !status.success() {
                return Err(anyhow!(
                    "Cargo build failed. Install 'cross' for easier cross-compilation: cargo install cross"
                ));
            }
        }
    } else {
        // Native build (already on Linux)
        let status = Command::new("cargo")
            .arg("build")
            .arg("--release")
            .current_dir(project_root)
            .status()
            .context("Failed to run cargo build")?;

        if !status.success() {
            return Err(anyhow!("Cargo build failed"));
        }
    }

    Ok(())
}

/// Find the workspace root by walking up the directory tree
/// For monorepos with sibling workspaces, this finds the parent directory containing all workspaces
fn find_workspace_root(project_root: &Path) -> Result<PathBuf> {
    let mut current = project_root;
    let mut workspace_root = None;

    // First, find the immediate workspace (e.g., audb/)
    loop {
        let cargo_toml = current.join("Cargo.toml");
        if cargo_toml.exists() {
            if let Ok(content) = fs::read_to_string(&cargo_toml) {
                if content.contains("[workspace]") {
                    workspace_root = Some(current.to_path_buf());
                    break;
                }
            }
        }

        match current.parent() {
            Some(parent) => current = parent,
            None => return Ok(project_root.to_path_buf()), // No workspace found, use project root
        }
    }

    // If we found a workspace, check if there are sibling workspaces (monorepo structure)
    if let Some(ws_root) = workspace_root {
        if let Some(parent) = ws_root.parent() {
            // Check if parent directory contains other workspace directories
            if let Ok(entries) = fs::read_dir(parent) {
                let mut workspace_count = 0;
                for entry in entries.flatten() {
                    if entry.path().is_dir() {
                        let cargo_toml = entry.path().join("Cargo.toml");
                        if cargo_toml.exists() {
                            if let Ok(content) = fs::read_to_string(&cargo_toml) {
                                if content.contains("[workspace]") {
                                    workspace_count += 1;
                                }
                            }
                        }
                    }
                }

                // If there are multiple workspaces at this level, use parent as monorepo root
                if workspace_count > 1 {
                    println!(
                        "Detected monorepo with {} sibling workspaces",
                        workspace_count
                    );
                    return Ok(parent.to_path_buf());
                }
            }
        }

        Ok(ws_root)
    } else {
        Ok(project_root.to_path_buf())
    }
}

/// Build Docker image using bollard
async fn build_docker_image(docker: &Docker, project_root: &Path, image_name: &str) -> Result<()> {
    // Create build context (tar of project directory)
    let tar_path = project_root.join(".audb").join("build-context.tar");
    fs::create_dir_all(tar_path.parent().unwrap())?;

    create_build_context_tar(project_root, &tar_path)?;

    // Read tar file
    let tar_data = fs::read(&tar_path).context("Failed to read build context tar")?;

    // Build image and stream progress using http-body-util
    use bytes::Bytes;
    use http_body_util::{Either, Full};
    let body = Full::new(Bytes::from(tar_data));

    let mut stream = docker.build_image(
        bollard::query_parameters::BuildImageOptions {
            t: Some(image_name.to_string()),
            dockerfile: "Dockerfile".to_string(),
            rm: true,
            ..Default::default()
        },
        None,
        Some(Either::Left(body)),
    );

    while let Some(msg) = stream.next().await {
        let info = msg.context("Docker build error")?;

        if let Some(stream) = info.stream {
            print!("{}", stream);
        }
        if let Some(error) = info.error {
            return Err(anyhow!("Docker build failed: {}", error));
        }
        if let Some(status) = info.status {
            if !status.is_empty() {
                println!("{}", status);
            }
        }
    }

    // Clean up tar
    let _ = fs::remove_file(tar_path);

    println!("Docker image '{}' built successfully", image_name);
    Ok(())
}

/// Build Docker image for workspace project
async fn build_docker_image_workspace(
    docker: &Docker,
    project_root: &Path,
    workspace_root: &Path,
    image_name: &str,
) -> Result<()> {
    // Calculate relative path from workspace to project
    let rel_project_path = project_root
        .strip_prefix(workspace_root)
        .context("Failed to calculate relative path")?;

    // Generate and write Dockerfile BEFORE creating tar
    let dockerfile_content = generate_workspace_dockerfile(
        project_root.file_name().unwrap().to_str().unwrap(),
        rel_project_path.to_str().unwrap(),
    );

    let dockerfile_path = workspace_root.join("Dockerfile.workspace");
    fs::write(&dockerfile_path, dockerfile_content)?;

    // Create build context (tar of entire workspace)
    let tar_path = project_root.join(".audb").join("build-context.tar");
    fs::create_dir_all(tar_path.parent().unwrap())?;

    println!(
        "Creating workspace build context from: {}",
        workspace_root.display()
    );
    create_workspace_build_context_tar(workspace_root, &tar_path)?;

    // Read tar file
    let tar_data = fs::read(&tar_path).context("Failed to read build context tar")?;

    // Build image and stream progress using http-body-util
    use bytes::Bytes;
    use http_body_util::{Either, Full};
    let body = Full::new(Bytes::from(tar_data));

    let mut stream = docker.build_image(
        bollard::query_parameters::BuildImageOptions {
            t: Some(image_name.to_string()),
            dockerfile: "Dockerfile.workspace".to_string(),
            rm: true,
            ..Default::default()
        },
        None,
        Some(Either::Left(body)),
    );

    while let Some(msg) = stream.next().await {
        let info = msg.context("Docker build error")?;

        if let Some(stream) = info.stream {
            print!("{}", stream);
        }
        if let Some(error) = info.error {
            return Err(anyhow!("Docker build failed: {}", error));
        }
        if let Some(status) = info.status {
            if !status.is_empty() {
                println!("{}", status);
            }
        }
    }

    // Clean up
    let _ = fs::remove_file(tar_path);
    let _ = fs::remove_file(dockerfile_path);

    println!("Docker image '{}' built successfully", image_name);
    Ok(())
}

/// Generate Dockerfile for workspace builds (runtime-only, uses pre-built binary)
fn generate_workspace_dockerfile(project_name: &str, rel_project_path: &str) -> String {
    // Determine binary path and platform based on OS and architecture
    // Note: workspace tar includes audb/ prefix
    let (binary_path, platform) = if cfg!(target_os = "macos") {
        if cfg!(target_arch = "aarch64") {
            (
                format!(
                    "audb/target/aarch64-unknown-linux-gnu/release/{}",
                    project_name
                ),
                "linux/arm64",
            )
        } else {
            (
                format!(
                    "audb/target/x86_64-unknown-linux-gnu/release/{}",
                    project_name
                ),
                "linux/amd64",
            )
        }
    } else {
        (
            format!("audb/target/release/{}", project_name),
            "linux/amd64",
        )
    };

    format!(
        r#"# Runtime-only Dockerfile for workspace project: {project_name}
# Generated by AuDB
# Uses pre-built binary from host

FROM --platform={platform} debian:bookworm-slim

# Install runtime dependencies
RUN apt-get update && \
    apt-get install -y ca-certificates && \
    rm -rf /var/lib/apt/lists/*

# Create app user
RUN useradd -m -u 1000 app

WORKDIR /app

# Copy pre-built binary from workspace target directory
COPY {binary_path} /app/{project_name}
RUN chmod +x /app/{project_name}

# Create data directory
RUN mkdir -p /app/data && chown -R app:app /app

# Switch to app user
USER app

# Expose port
EXPOSE 8080

# Set environment
ENV RUST_LOG=info

# Run the application
CMD ["/app/{project_name}"]
"#,
        project_name = project_name,
        binary_path = binary_path,
        platform = platform
    )
}

/// Create tar archive of workspace for Docker build
fn create_workspace_build_context_tar(workspace_root: &Path, tar_path: &Path) -> Result<()> {
    use std::process::Command;

    // Only include the workspace directories we actually need, not everything in parent
    let required_dirs = ["audb", "manifold", "hyperQL", "tessera"];

    let mut tar_cmd = Command::new("tar");
    tar_cmd
        .arg("czf")
        .arg(tar_path)
        .arg("--exclude=target/debug")
        .arg("--exclude=target/release")
        .arg("--exclude=.git")
        .arg("--exclude=.audb")
        .arg("--exclude=node_modules")
        .arg("--exclude=.venv")
        .arg("--exclude=.DS_Store")
        .arg("--exclude=*.tar")
        .arg("--exclude=*.tar.gz")
        .arg("--no-xattrs") // Exclude macOS extended attributes
        .arg("-C")
        .arg(workspace_root);

    // Add only required directories
    for dir in &required_dirs {
        let dir_path = workspace_root.join(dir);
        if dir_path.exists() {
            tar_cmd.arg(dir);
        }
    }

    // Include the cross-compiled binary directory if it exists
    let cross_target_dir = workspace_root.join("target/x86_64-unknown-linux-gnu/release");
    if cross_target_dir.exists() {
        tar_cmd.arg("target/x86_64-unknown-linux-gnu/release");
    }

    // Also include Dockerfile.workspace
    tar_cmd.arg("Dockerfile.workspace");

    let status = tar_cmd
        .status()
        .context("Failed to create workspace tar archive")?;

    if !status.success() {
        return Err(anyhow!("Failed to create workspace build context tar"));
    }

    println!("Workspace context created ({})", humanize_size(tar_path)?);

    Ok(())
}

/// Create tar archive of build context
fn create_build_context_tar(project_root: &Path, tar_path: &Path) -> Result<()> {
    use std::process::Command;

    let status = Command::new("tar")
        .arg("czf")
        .arg(tar_path)
        .arg("--exclude=target")
        .arg("--exclude=.git")
        .arg("--exclude=.audb")
        .arg("--exclude=node_modules")
        .arg("--no-xattrs") // Exclude macOS extended attributes
        .arg("-C")
        .arg(project_root)
        .arg(".")
        .status()
        .context("Failed to create tar archive")?;

    if !status.success() {
        return Err(anyhow!("Failed to create build context tar"));
    }

    Ok(())
}

/// Human-readable file size
fn humanize_size(path: &Path) -> Result<String> {
    let metadata = fs::metadata(path)?;
    let bytes = metadata.len();

    if bytes < 1024 {
        Ok(format!("{} B", bytes))
    } else if bytes < 1024 * 1024 {
        Ok(format!("{:.1} KB", bytes as f64 / 1024.0))
    } else if bytes < 1024 * 1024 * 1024 {
        Ok(format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0)))
    } else {
        Ok(format!(
            "{:.1} GB",
            bytes as f64 / (1024.0 * 1024.0 * 1024.0)
        ))
    }
}

/// Create Docker container
async fn create_container(
    docker: &Docker,
    image_name: &str,
    container_name: &str,
    port: u16,
    env_vars: &HashMap<String, String>,
    volumes: &HashMap<String, String>,
) -> Result<String> {
    // Build environment variables
    let env: Vec<String> = env_vars
        .iter()
        .map(|(k, v)| format!("{}={}", k, v))
        .collect();

    // Build port bindings
    let mut port_bindings = HashMap::new();
    let container_port = format!("{}/tcp", port);
    port_bindings.insert(
        container_port,
        Some(vec![PortBinding {
            host_ip: Some("0.0.0.0".to_string()),
            host_port: Some(port.to_string()),
        }]),
    );

    // Build volume bindings (source:destination format)
    let bindings: Vec<String> = volumes
        .iter()
        .map(|(src, dst)| format!("{}:{}", src, dst))
        .collect();

    let host_config = HostConfig {
        port_bindings: Some(port_bindings),
        binds: if bindings.is_empty() {
            None
        } else {
            Some(bindings)
        },
        restart_policy: Some(bollard::models::RestartPolicy {
            name: Some(bollard::models::RestartPolicyNameEnum::UNLESS_STOPPED),
            maximum_retry_count: None,
        }),
        ..Default::default()
    };

    let config = ContainerCreateBody {
        image: Some(image_name.to_string()),
        env: if env.is_empty() { None } else { Some(env) },
        host_config: Some(host_config),
        ..Default::default()
    };

    let response = docker
        .create_container(
            Some(bollard::query_parameters::CreateContainerOptions {
                name: Some(container_name.to_string()),
                ..Default::default()
            }),
            config,
        )
        .await
        .context("Failed to create container")?;

    Ok(response.id)
}

/// Start Docker container
async fn start_container(docker: &Docker, container_id: &str) -> Result<()> {
    docker
        .start_container(
            container_id,
            None::<bollard::query_parameters::StartContainerOptions>,
        )
        .await
        .context("Failed to start container")?;

    Ok(())
}

/// Stop and remove Docker container
pub async fn stop(project_root: &Path) -> Result<()> {
    let state = DeploymentState::load(project_root).context("No deployment state found")?;

    if state.target != DeploymentTarget::Docker {
        return Err(anyhow!("Not a Docker deployment"));
    }

    let docker =
        Docker::connect_with_local_defaults().context("Failed to connect to Docker daemon")?;

    println!("Stopping container '{}'...", state.service_label);

    stop_container_by_id(&docker, &state.service_label).await?;

    println!("Container stopped and removed");

    // Remove state file
    let state_path = project_root.join(".audb").join("deploy.toml");
    if state_path.exists() {
        fs::remove_file(&state_path).context("Failed to remove state file")?;
    }

    Ok(())
}

/// Stop container by ID
async fn stop_container_by_id(docker: &Docker, container_id: &str) -> Result<()> {
    // Stop container
    let _ = docker
        .stop_container(
            container_id,
            None::<bollard::query_parameters::StopContainerOptions>,
        )
        .await
        .context("Failed to stop container");

    // Remove container
    docker
        .remove_container(
            container_id,
            Some(bollard::query_parameters::RemoveContainerOptions {
                force: true,
                ..Default::default()
            }),
        )
        .await
        .context("Failed to remove container")?;

    Ok(())
}

/// Get container status
pub async fn status(project_root: &Path) -> Result<()> {
    let state = DeploymentState::load(project_root).context("No deployment state found")?;

    if state.target != DeploymentTarget::Docker {
        return Err(anyhow!("Not a Docker deployment"));
    }

    println!("Service: {}", state.service_label);
    println!("Project: {}", state.project_name);
    println!(
        "Deployed at: {}",
        state.deployed_at.format("%Y-%m-%d %H:%M:%S UTC")
    );

    let docker =
        Docker::connect_with_local_defaults().context("Failed to connect to Docker daemon")?;

    let container = docker
        .inspect_container(
            &state.service_label,
            None::<bollard::query_parameters::InspectContainerOptions>,
        )
        .await
        .context("Failed to inspect container")?;

    if let Some(name) = container.name {
        println!("Container: {}", name);
    }
    if let Some(config) = container.config {
        if let Some(image) = config.image {
            println!("Image: {}", image);
        }
    }

    if let Some(container_state) = container.state {
        let status = container_state
            .status
            .unwrap_or(ContainerStateStatusEnum::EMPTY);
        println!("Status: {:?}", status);

        if let Some(running) = container_state.running {
            println!("Running: {}", running);
        }
        if let Some(started_at) = container_state.started_at {
            println!("Started at: {}", started_at);
        }
    }

    Ok(())
}

/// Stream container logs
pub async fn logs(project_root: &Path, follow: bool, tail: Option<String>) -> Result<()> {
    let state = DeploymentState::load(project_root).context("No deployment state found")?;

    if state.target != DeploymentTarget::Docker {
        return Err(anyhow!("Not a Docker deployment"));
    }

    let docker =
        Docker::connect_with_local_defaults().context("Failed to connect to Docker daemon")?;

    println!("Fetching logs for container '{}'...\n", state.project_name);

    let options = bollard::query_parameters::LogsOptions {
        follow: follow,
        stdout: true,
        stderr: true,
        tail: tail.unwrap_or_else(|| "100".to_string()),
        ..Default::default()
    };

    let mut stream = docker.logs(&state.service_label, Some(options));

    while let Some(log) = stream.next().await {
        match log {
            Ok(LogOutput::StdOut { message }) => {
                print!("{}", String::from_utf8_lossy(&message));
            }
            Ok(LogOutput::StdErr { message }) => {
                eprint!("{}", String::from_utf8_lossy(&message));
            }
            Ok(_) => {}
            Err(e) => {
                eprintln!("Error reading logs: {}", e);
                break;
            }
        }
    }

    Ok(())
}

/// Restart container
pub async fn restart(project_root: &Path) -> Result<()> {
    let state = DeploymentState::load(project_root).context("No deployment state found")?;

    if state.target != DeploymentTarget::Docker {
        return Err(anyhow!("Not a Docker deployment"));
    }

    let docker =
        Docker::connect_with_local_defaults().context("Failed to connect to Docker daemon")?;

    println!("Restarting container '{}'...", state.service_label);

    docker
        .restart_container(
            &state.service_label,
            None::<bollard::query_parameters::RestartContainerOptions>,
        )
        .await
        .context("Failed to restart container")?;

    println!("Container restarted successfully");

    Ok(())
}

/// Perform health check
async fn perform_health_check(
    health_check: &crate::commands::deploy::config::HealthCheckConfig,
    port: u16,
) -> Result<()> {
    use std::time::Duration;
    use tokio::time::sleep;

    let url = format!("http://localhost:{}{}", port, health_check.endpoint);
    let client = reqwest::Client::new();

    // Parse timeout and interval (simple seconds for now)
    let timeout_secs: u64 = health_check
        .timeout
        .trim_end_matches('s')
        .parse()
        .unwrap_or(60);
    let interval_secs: u64 = health_check
        .interval
        .trim_end_matches('s')
        .parse()
        .unwrap_or(5);

    let mut attempts = 0;
    let max_attempts = timeout_secs / interval_secs;

    loop {
        attempts += 1;

        match client.get(&url).send().await {
            Ok(response) => {
                if response.status().is_success() {
                    return Ok(());
                } else {
                    println!(
                        "Health check returned status: {} (attempt {}/{})",
                        response.status(),
                        attempts,
                        max_attempts
                    );
                }
            }
            Err(e) => {
                println!(
                    "Health check failed: {} (attempt {}/{})",
                    e, attempts, max_attempts
                );
            }
        }

        if attempts >= max_attempts {
            return Err(anyhow!(
                "Health check timed out after {} attempts",
                attempts
            ));
        }

        sleep(Duration::from_secs(interval_secs)).await;
    }
}