clawgarden-cli 0.7.3

ClawGarden CLI - Multi-bot/multi-agent Garden management tool
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
//! Docker Compose file generator for ClawGarden
//!
//! Generates per-garden docker-compose.yml and .env files.
//! Also provides container lifecycle and inspection helpers.

use anyhow::{Context, Result};
use std::path::PathBuf;

use crate::garden::load_gardens;
use crate::providers::ProviderManifest;
use clawgarden_proto::config::{generate_default_toml, SecretsToml, TomlConfig};
use std::sync::Arc;

// ── Data types ───────────────────────────────────────────────────────────────

/// Telegram bot configuration
#[derive(Debug, Clone)]
pub struct BotConfig {
    pub name: String,
    pub role: String,
    pub token: String,
    /// Telegram @username (auto-discovered by entrypoint or set manually)
    pub username: String,
    /// Priority for turn ordering (lower = higher priority)
    pub priority: u32,
    /// Whether this agent is active
    pub enabled: bool,
}

impl Default for BotConfig {
    fn default() -> Self {
        Self {
            name: String::new(),
            role: "assistant".to_string(),
            token: String::new(),
            username: String::new(),
            priority: 100,
            enabled: true,
        }
    }
}

impl BotConfig {
    /// Returns the identifier suffix for environment variable names.
    ///
    /// Uses the Telegram bot username (always ASCII `[a-zA-Z0-9_]`) when
    /// available — resolved via `getMe` API during onboarding.
    /// Falls back to the display name uppercased (may fail for non-ASCII).
    pub fn env_id(&self) -> String {
        if !self.username.is_empty() {
            self.username.to_uppercase()
        } else {
            // Fallback: slugify the display name to ASCII-safe identifier
            let slug: String = self
                .name
                .chars()
                .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
                .collect();
            if slug.is_empty() {
                // Last resort: use a hash-based identifier
                use std::hash::{Hash, Hasher};
                use std::collections::hash_map::DefaultHasher;
                let mut hasher = DefaultHasher::new();
                self.name.hash(&mut hasher);
                format!("BOT{:x}", hasher.finish())
            } else {
                slug.to_uppercase()
            }
        }
    }
}

/// Provider configuration entry
#[derive(Debug, Clone)]
pub struct ProviderEntry {
    pub provider: Arc<ProviderManifest>,
    pub auth_method_id: String,
    pub api_key: String,
    pub model: String,
}

/// Garden creation config
#[derive(Debug, Clone)]
pub struct GardenConfig {
    pub name: String,
    pub telegram_group_id: String,
    pub bots: Vec<BotConfig>,
    pub providers: Vec<ProviderEntry>,
}

/// Container status information retrieved via `docker inspect`.
#[derive(Debug, Clone)]
pub struct ContainerStatus {
    pub name: String,
    pub running: bool,
    pub status: String,        // "Up 2 hours", "Exited (0) 5 min ago", etc.
    pub healthy: Option<bool>, // None = no healthcheck defined
    pub started_at: Option<String>,
    pub image: String,
    #[allow(dead_code)]
    pub ports: Vec<String>,
}

// ── Config generation ────────────────────────────────────────────────────────

impl GardenConfig {
    /// Generate docker-compose.yml content
    pub fn generate_compose(&self) -> String {
        // Build bot env vars
        let mut bot_envs = String::new();
        for bot in self.bots.iter() {
            let key = format!("TELEGRAM_BOT_TOKEN_{}", bot.env_id());
            bot_envs.push_str(&format!("      {}: \"${{{}}}\"\n", key, key));
        }

        // Build provider env vars (API keys + models)
        let mut provider_envs = String::new();
        for entry in &self.providers {
            let key = format!("{}_API_KEY", entry.provider.id.to_uppercase());
            provider_envs.push_str(&format!("      {}: \"${{{}}}\"\n", key, key));
            let model_key = format!("{}_MODEL", entry.provider.id.to_uppercase());
            provider_envs.push_str(&format!("      {}: \"${{{}}}\"\n", model_key, model_key));
        }

        format!(
            r#"services:
  garden:
    container_name: {container_name}
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    environment:
      # Telegram bot tokens
{bot_envs}
      # Telegram group configuration
      TELEGRAM_GROUP_ID: "{telegram_group_id}"
      TELEGRAM_INGRESS_BOT: "{ingress_bot}"
      # Provider API keys (for backwards compat)
{provider_envs}
      # Garden configuration
      GARDEN_WORKSPACE: /workspace
      RUST_LOG: info
      # LLM backend (defaults to provider-specific env vars for backwards compat)
      LLM_API_BASE: "${{LLM_API_BASE:-}}"
      LLM_API_KEY: "${{LLM_API_KEY:-}}"
      LLM_MODEL: "${{LLM_MODEL:-}}"
      # Turn-based group chat settings
      ROUND_MAX_TURNS: "${{ROUND_MAX_TURNS:-3}}"
      TURN_DECISION_WINDOW_MS: "${{TURN_DECISION_WINDOW_MS:-2000}}"
      TURN_RESPONSE_TIMEOUT_MS: "${{TURN_RESPONSE_TIMEOUT_MS:-10000}}"
      SELECTION_CONFIDENCE_THRESHOLD: "${{SELECTION_CONFIDENCE_THRESHOLD:-0.3}}"
      # Team members for agent awareness
      TEAM_MEMBERS: "${{TEAM_MEMBERS:-}}"
      # Metrics (optional)
      METRICS_PORT: 8080
    volumes:
      - ./workspace:/workspace
      - ./clawgarden.toml:/app/clawgarden.toml:ro
      - ./pi-auth.json:/home/garden/.pi/agent/auth.json:ro
    networks:
      - garden-net
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 30s

networks:
  garden-net:
    name: {network_name}
    driver: bridge
"#,
            container_name = format!("garden-{}", self.name),
            bot_envs = bot_envs,
            telegram_group_id = self.telegram_group_id,
            ingress_bot = self
                .bots
                .first()
                .map(|b| if b.username.is_empty() { b.name.as_str() } else { b.username.as_str() })
                .unwrap_or("ingress"),
            provider_envs = provider_envs,
            network_name = format!("garden-net-{}", self.name)
        )
    }

    /// Generate .env file content — derived from secrets.
    /// This is a Docker compatibility layer; the real source is .secrets.toml.
    pub fn generate_env(&self) -> String {
        // Build secrets from current config
        let secrets = self.generate_secrets_toml();
        let parsed: clawgarden_proto::config::SecretsToml =
            toml::from_str(&secrets).unwrap_or_default();
        parsed.to_env_content()
    }

    /// Write docker-compose.yml and .env to garden directory
    pub fn write(&self) -> Result<(PathBuf, PathBuf)> {
        let registry = load_gardens()?;
        let garden_dir = registry.garden_dir(&self.name);
        let workspace_dir = registry.workspace_dir(&self.name);

        // Create directories
        std::fs::create_dir_all(&garden_dir).context("Failed to create garden directory")?;
        std::fs::create_dir_all(workspace_dir.join("agents"))
            .context("Failed to create agents directory")?;
        std::fs::create_dir_all(workspace_dir.join("data"))
            .context("Failed to create data directory")?;
        std::fs::create_dir_all(workspace_dir.join("logs"))
            .context("Failed to create logs directory")?;

        // Write docker-compose.yml
        let compose_path = registry.compose_file(&self.name);
        std::fs::write(&compose_path, self.generate_compose())
            .context("Failed to write docker-compose.yml")?;

        // Write Dockerfile
        let dockerfile_path = garden_dir.join("Dockerfile");
        std::fs::write(&dockerfile_path, self.generate_dockerfile())
            .context("Failed to write Dockerfile")?;

        // Write entrypoint.sh
        let entrypoint_path = garden_dir.join("entrypoint.sh");
        std::fs::write(&entrypoint_path, self.generate_entrypoint())
            .context("Failed to write entrypoint.sh")?;

        // Write .env
        let env_path = registry.env_file(&self.name);
        std::fs::write(&env_path, self.generate_env()).context("Failed to write .env file")?;

        // Write pi auth.json
        let auth_json_path = garden_dir.join("pi-auth.json");
        let auth_json_content = self.generate_auth_json();
        std::fs::write(&auth_json_path, auth_json_content)
            .context("Failed to write pi-auth.json")?;

        // Write registry.json
        let registry_path = workspace_dir.join("agents/registry.json");
        let registry_json = self.generate_registry_json();
        std::fs::write(&registry_path, registry_json).context("Failed to write registry.json")?;

        // Write allowlist
        let allowlist_path = workspace_dir.join("agents/.allowlist");
        std::fs::write(&allowlist_path, "pi-coding-agent\n")
            .context("Failed to write allowlist")?;

        // Write clawgarden.toml
        let config_path = garden_dir.join("clawgarden.toml");
        std::fs::write(&config_path, self.generate_clawgarden_toml())
            .context("Failed to write clawgarden.toml")?;

        // Write .secrets.toml
        let secrets_path = garden_dir.join(".secrets.toml");
        std::fs::write(&secrets_path, self.generate_secrets_toml())
            .context("Failed to write .secrets.toml")?;

        Ok((compose_path, env_path))
    }

    /// Generate pi auth.json content
    /// Generate clawgarden.toml content with actual configured values
    pub fn generate_clawgarden_toml(&self) -> String {
        let mut config = TomlConfig::default();

        // Telegram section with actual values
        config.telegram.group_id = if self.telegram_group_id.is_empty() {
            None
        } else {
            Some(self.telegram_group_id.clone())
        };
        config.telegram.ingress_bot = Some(
            self.bots
                .first()
                .map(|b| if b.username.is_empty() { b.name.as_str() } else { b.username.as_str() })
                .unwrap_or("alex")
                .to_string(),
        );

        toml::to_string_pretty(&config).unwrap_or_else(|_| generate_default_toml())
    }

    /// Generate .secrets.toml content from bots and providers
    pub fn generate_secrets_toml(&self) -> String {
        let mut secrets = SecretsToml::default();

        // Bot tokens
        for bot in &self.bots {
            let key = format!("TELEGRAM_BOT_TOKEN_{}", bot.env_id());
            secrets.set(key, bot.token.clone());
        }

        // Provider keys
        for entry in &self.providers {
            let key = format!("{}_API_KEY", entry.provider.id.to_uppercase());
            secrets.set(key, entry.api_key.clone());
            let model_key = format!("{}_MODEL", entry.provider.id.to_uppercase());
            secrets.set(model_key, entry.model.clone());
        }

        // Group ID
        if !self.telegram_group_id.is_empty() {
            secrets.set(
                "TELEGRAM_GROUP_ID".to_string(),
                self.telegram_group_id.clone(),
            );
        }

        toml::to_string_pretty(&secrets).unwrap_or_else(|_| "[secrets]\n".to_string())
    }

    /// Generate Dockerfile for the garden runtime
    pub fn generate_dockerfile(&self) -> String {
        indoc::indoc!(r#"
            FROM rust:slim AS builder
            RUN apt-get update && apt-get install -y pkg-config libssl-dev && rm -rf /var/lib/apt/lists/*
            ARG CLAWGARDEN_VERSION=0.7.0
            RUN cargo install clawgarden-bus clawgarden-agent --version ${CLAWGARDEN_VERSION}

            FROM debian:trixie-slim
            WORKDIR /app

            RUN apt-get update && apt-get install -y --no-install-recommends \
                ca-certificates curl sqlite3 bash nodejs npm \
                && rm -rf /var/lib/apt/lists/*

            ARG PI_VERSION=latest
            # Note: npm supports 'latest' unlike cargo
            RUN npm install -g pi-coding-agent@${PI_VERSION}

            COPY --from=builder /usr/local/cargo/bin/clawgarden-bus /app/clawgarden-bus
            COPY --from=builder /usr/local/cargo/bin/clawgarden-agent /app/clawgarden-agent

            RUN groupadd -g 10001 garden && \
                useradd -r -u 10001 -g garden -s /bin/bash -d /app garden
            RUN mkdir -p /workspace/agents /workspace/data /workspace/logs /workspace/skills && \
                chown -R garden:garden /app /workspace

            COPY entrypoint.sh /app/entrypoint.sh
            RUN chmod +x /app/entrypoint.sh

            USER garden
            ENV GARDEN_WORKSPACE=/workspace
            ENV RUST_LOG=info
            ENV CLAWGARDEN_SOCKET=/tmp/clawgarden.sock
            ENV CLAWGARDEN_REGISTRY=/workspace/agents/registry.json
            ENV CLAWGARDEN_DB=/workspace/data/clawgarden.db
            EXPOSE 8080

            ENTRYPOINT ["/app/entrypoint.sh"]
        "#).trim_start().to_string()
    }

    /// Generate entrypoint script
    ///
    /// Reads registry.json to start agents by their display name,
    /// resolving tokens from env vars that use Telegram usernames.
    /// No manual username configuration needed — just bot tokens.
    pub fn generate_entrypoint(&self) -> String {
        indoc::indoc!(r#"
            #!/bin/bash
            set -e

            REGISTRY=/workspace/agents/registry.json
            if [ ! -f "$REGISTRY" ]; then
                echo "ERROR: $REGISTRY not found"; exit 1
            fi

            MEMBERS=""

            # Extract (name token_env) pairs from registry.json using node (installed in image)
            PAIRS=$(node -e "
                const reg = JSON.parse(require('fs').readFileSync('$REGISTRY','utf8'));
                reg.agents.forEach(a => console.log(a.name + '\t' + a.bot.token_env));
            ")

            echo "Loaded agents from registry"

            while IFS=$'\t' read -r name token_env; do
                [ -z "$name" ] && continue

                token=$(printenv "$token_env" 2>/dev/null || true)
                if [ -z "$token" ]; then
                    echo "WARN: No token for agent '$name' (expected env $token_env)"
                    continue
                fi

                # Resolve Telegram username via getMe
                USERNAME=$(curl -sf "https://api.telegram.org/bot${token}/getMe" \
                    | node -e "let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>{try{console.log(JSON.parse(d).result.username)}catch{}})" 2>/dev/null || true)

                if [ -n "$USERNAME" ]; then
                    MEMBERS="${MEMBERS}${name}:@${USERNAME},"
                    # Update registry.json with discovered username
                    node -e "
                        const fs=require('fs');
                        const r=JSON.parse(fs.readFileSync('$REGISTRY','utf8'));
                        r.agents.filter(a=>a.name==='$name').forEach(a=>a.bot.username='$USERNAME');
                        fs.writeFileSync('$REGISTRY',JSON.stringify(r,null,2));
                    " 2>/dev/null || true
                    echo "  $name -> @${USERNAME}"
                else
                    MEMBERS="${MEMBERS}${name},"
                    echo "  WARN: Could not resolve username for '$name'"
                fi

                # Start agent process
                export TELEGRAM_BOT_USERNAME="$USERNAME"
                export TEAM_MEMBERS="$MEMBERS"
                /app/clawgarden-agent --agent-name "$name" &
                echo "  Agent '$name' started (@${USERNAME:-?})"
                unset TELEGRAM_BOT_USERNAME
            done <<< "$PAIRS"

            echo "Team: $MEMBERS"

            # Start bus (foreground)
            exec /app/clawgarden-bus
        "#).trim_start().to_string()
    }

    pub fn generate_auth_json(&self) -> String {
        use crate::providers::PiAuthJson;

        let provider_keys: Vec<(String, String)> = self
            .providers
            .iter()
            .map(|e| (e.provider.id.clone(), e.api_key.clone()))
            .collect();

        let auth = PiAuthJson::new(&provider_keys);
        auth.to_json_string().unwrap_or_else(|_| "{}".to_string())
    }

    /// Generate registry.json content
    pub fn generate_registry_json(&self) -> String {
        let mut agents = vec![];

        for bot in &self.bots {
            let mut agent = serde_json::json!({
                "name": bot.name,
                "role": bot.role,
                "enabled": bot.enabled,
                "priority": bot.priority,
                "bot": {
                    "token_env": format!("TELEGRAM_BOT_TOKEN_{}", bot.env_id())
                }
            });
            if !bot.username.is_empty() {
                agent["bot"]["username"] = serde_json::json!(bot.username);
            }
            agents.push(agent);
        }

        // Provider entries
        let provider_entries: Vec<serde_json::Value> = self
            .providers
            .iter()
            .map(|entry| {
                serde_json::json!({
                    "id": entry.provider.id,
                    "auth_method": entry.auth_method_id,
                    "model": entry.model,
                })
            })
            .collect();

        let registry = serde_json::json!({
            "version": 1,
            "telegram": {
                "group_id": self.telegram_group_id,
                "ingress_bot": self.bots.first().map(|b| if b.username.is_empty() { b.name.as_str() } else { b.username.as_str() }).unwrap_or("ingress")
            },
            "agents": agents,
            "providers": provider_entries
        });

        serde_json::to_string_pretty(&registry).unwrap()
    }
}

// ── Container lifecycle ──────────────────────────────────────────────────────

/// Start a garden
pub fn start_garden(name: &str, build: bool) -> Result<()> {
    let registry = load_gardens()?;

    if !registry.exists(name) {
        anyhow::bail!("Garden '{}' not found. Run 'garden new' first.", name);
    }

    let compose_file = registry.compose_file(name);

    if !compose_file.exists() {
        anyhow::bail!("Garden '{}' not initialized. Run 'garden new' first.", name);
    }

    // Load .env and export variables for docker-compose
    let env_file = registry.env_file(name);
    load_env_file(&env_file)?;

    crate::ui::spinner(&format!("Starting garden '{}'...", name), 600);

    let up_args = if build {
        vec!["up", "-d", "--build"]
    } else {
        vec!["up", "-d"]
    };

    let result = std::process::Command::new(docker_compose_bin())
        .args(compose_args(compose_file.to_str().unwrap_or(""), &up_args))
        .current_dir(registry.garden_dir(name))
        .status();

    match result {
        Ok(status) if status.success() => {
            println!();
            crate::ui::success(&format!("Garden '{}' is blooming!", name));
            println!("  Container: garden-{}", name);
            Ok(())
        }
        Ok(status) => {
            anyhow::bail!("Failed to start garden (exit code: {:?})", status.code());
        }
        Err(e) => {
            anyhow::bail!("Failed to execute docker-compose: {}", e);
        }
    }
}

/// Stop a garden
pub fn stop_garden(name: &str) -> Result<()> {
    let registry = load_gardens()?;

    if !registry.exists(name) {
        anyhow::bail!("Garden '{}' not found", name);
    }

    let compose_file = registry.compose_file(name);

    if !compose_file.exists() {
        println!("Garden '{}' is not initialized.", name);
        return Ok(());
    }

    crate::ui::spinner(&format!("Stopping garden '{}'...", name), 400);

    let result = std::process::Command::new(docker_compose_bin())
        .args(compose_args(compose_file.to_str().unwrap_or(""), &["down"]))
        .current_dir(registry.garden_dir(name))
        .status();

    match result {
        Ok(status) if status.success() => {
            println!();
            crate::ui::success(&format!("Garden '{}' put to rest.", name));
            Ok(())
        }
        Ok(status) => {
            anyhow::bail!("Failed to stop garden (exit code: {:?})", status.code());
        }
        Err(e) => {
            anyhow::bail!("Failed to execute docker-compose: {}", e);
        }
    }
}

/// Restart a garden (down + up)
pub fn restart_garden(name: &str) -> Result<()> {
    crate::ui::spinner(&format!("Restarting garden '{}'...", name), 500);
    stop_garden_quiet(name)?;
    start_garden(name, false)
}

/// Get logs from a garden
pub fn garden_logs(name: &str, follow: bool, lines: usize) -> Result<std::process::ExitStatus> {
    let registry = load_gardens()?;

    if !registry.exists(name) {
        anyhow::bail!("Garden '{}' not found", name);
    }

    let compose_file = registry.compose_file(name);

    if !compose_file.exists() {
        anyhow::bail!("Garden '{}' is not initialized", name);
    }

    let mut args = vec![
        "-f".to_string(),
        compose_file.to_string_lossy().to_string(),
        "logs".to_string(),
    ];

    if follow {
        args.push("--follow".to_string());
    }

    args.push(format!("--tail={}", lines));

    let result = std::process::Command::new(docker_compose_bin())
        .args(&args)
        .current_dir(registry.garden_dir(name))
        .status();

    Ok(result?)
}

/// Execute command in a garden
pub fn garden_exec(name: &str, command: &[String]) -> Result<std::process::ExitStatus> {
    let registry = load_gardens()?;

    if !registry.exists(name) {
        anyhow::bail!("Garden '{}' not found", name);
    }

    let compose_file = registry.compose_file(name);

    if !compose_file.exists() {
        anyhow::bail!("Garden '{}' is not initialized", name);
    }

    let mut args = vec![
        "-f".to_string(),
        compose_file.to_string_lossy().to_string(),
        "exec".to_string(),
        "-T".to_string(),
        "garden".to_string(),
    ];
    args.extend(command.to_vec());

    let result = std::process::Command::new(docker_compose_bin())
        .args(&args)
        .current_dir(registry.garden_dir(name))
        .status();

    Ok(result?)
}

/// Open an interactive shell in the garden container
pub fn garden_shell(name: &str, shell: &str) -> Result<std::process::ExitStatus> {
    let registry = load_gardens()?;

    if !registry.exists(name) {
        anyhow::bail!("Garden '{}' not found", name);
    }

    let compose_file = registry.compose_file(name);

    if !compose_file.exists() {
        anyhow::bail!("Garden '{}' is not initialized", name);
    }

    let args = vec![
        "-f".to_string(),
        compose_file.to_string_lossy().to_string(),
        "exec".to_string(),
        "garden".to_string(),
        shell.to_string(),
    ];

    let result = std::process::Command::new(docker_compose_bin())
        .args(&args)
        .current_dir(registry.garden_dir(name))
        .status();

    Ok(result?)
}

// ── Container inspection ─────────────────────────────────────────────────────

/// Inspect a running container and return its status.
pub fn inspect_container(name: &str) -> Result<ContainerStatus> {
    let container_name = format!("garden-{}", name);

    let output = std::process::Command::new("docker")
        .args([
            "inspect",
            "--format",
            "{{.State.Running}}|{{.State.Status}}|{{.State.StartedAt}}|{{.Config.Image}}|{{range $p, $conf := .NetworkSettings.Ports}}{{if $conf}}{{$p}} {{end}}{{end}}",
            &container_name,
        ])
        .output();

    match output {
        Ok(out) if out.status.success() => {
            let stdout = String::from_utf8_lossy(&out.stdout);
            let parts: Vec<&str> = stdout.trim().split('|').collect();

            let running = parts.first().map(|s| *s == "true").unwrap_or(false);
            let status_raw = parts.get(1).map(|s| *s).unwrap_or("unknown");
            let started_at = parts.get(2).map(|s| s.to_string());
            let image = parts.get(3).map(|s| s.to_string()).unwrap_or_default();
            let ports_str = parts.get(4).map(|s| s.to_string()).unwrap_or_default();
            let ports: Vec<String> = if ports_str.is_empty() {
                vec![]
            } else {
                ports_str
                    .split_whitespace()
                    .map(|s| s.to_string())
                    .collect()
            };

            // Derive human-readable status
            let status = if running {
                format!(
                    "Up{}",
                    started_at
                        .as_ref()
                        .map(|t| format!(" since {}", t))
                        .unwrap_or_default()
                )
            } else {
                status_raw.to_string()
            };

            // Check health
            let healthy = check_health(&container_name);

            Ok(ContainerStatus {
                name: container_name,
                running,
                status,
                healthy,
                started_at,
                image,
                ports,
            })
        }
        Ok(_) => {
            // Container doesn't exist
            Ok(ContainerStatus {
                name: container_name,
                running: false,
                status: "not created".to_string(),
                healthy: None,
                started_at: None,
                image: String::new(),
                ports: vec![],
            })
        }
        Err(e) => {
            anyhow::bail!("Failed to inspect container: {}", e);
        }
    }
}

/// Check health status from docker healthcheck.
fn check_health(container_name: &str) -> Option<bool> {
    let output = std::process::Command::new("docker")
        .args([
            "inspect",
            "--format",
            "{{.State.Health.Status}}",
            container_name,
        ])
        .output();

    match output {
        Ok(out) if out.status.success() => {
            let stdout = String::from_utf8_lossy(&out.stdout);
            match stdout.trim() {
                "healthy" => Some(true),
                "unhealthy" => Some(false),
                "starting" => None, // still starting up
                _ => None,
            }
        }
        _ => None, // No healthcheck defined or container not running
    }
}

/// Get container resource usage (CPU %, memory) via `docker stats --no-stream`.
pub fn container_stats(name: &str) -> Option<String> {
    let container_name = format!("garden-{}", name);
    let output = std::process::Command::new("docker")
        .args([
            "stats",
            "--no-stream",
            "--format",
            "{{.CPUPerc}} CPU · {{.MemUsage}}",
            &container_name,
        ])
        .output()
        .ok()?;

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        let line = stdout.lines().nth(1).unwrap_or("").trim();
        if !line.is_empty() {
            return Some(line.to_string());
        }
    }
    None
}

// ── Internal helpers ─────────────────────────────────────────────────────────

/// Detect the correct docker-compose binary (cached after first call).
/// Prefers V2 plugin (`docker compose`) over standalone (`docker-compose`).
pub fn docker_compose_bin() -> &'static str {
    use once_cell::sync::Lazy;
    static BIN: Lazy<&str> = Lazy::new(|| {
        // Try V2 plugin first: `docker compose version`
        if let Ok(out) = std::process::Command::new("docker")
            .args(["compose", "version"])
            .output()
        {
            if out.status.success() {
                return "docker";
            }
        }
        // Fall back to standalone binary
        "docker-compose"
    });
    *BIN
}

/// Build compose args with the correct subcommand prefix.
/// V2: ["compose", "-f", file, ...]
/// V1: ["-f", file, ...]
pub fn compose_args(file: &str, subcmd: &[&str]) -> Vec<String> {
    let bin = docker_compose_bin();
    let mut args = Vec::new();
    if bin == "docker" {
        args.push("compose".to_string());
    }
    args.push("-f".to_string());
    args.push(file.to_string());
    for s in subcmd {
        args.push(s.to_string());
    }
    args
}

/// Stop a garden without printing success messages (used by restart).
fn stop_garden_quiet(name: &str) -> Result<()> {
    let registry = load_gardens()?;
    if !registry.exists(name) {
        return Ok(());
    }
    let compose_file = registry.compose_file(name);
    if !compose_file.exists() {
        return Ok(());
    }
    let _ = std::process::Command::new(docker_compose_bin())
        .args(compose_args(compose_file.to_str().unwrap_or(""), &["down"]))
        .current_dir(registry.garden_dir(name))
        .output();
    Ok(())
}

/// Load .env file and set environment variables
pub fn load_env_file(path: &PathBuf) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }

    let content = std::fs::read_to_string(path).context("Failed to read .env file")?;

    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        if let Some((key, value)) = line.split_once('=') {
            let key = key.trim();
            let value = value.trim();
            std::env::set_var(key, value);
        }
    }

    Ok(())
}