arcbox-api 0.0.1-alpha.1

API server for ArcBox (gRPC + REST)
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
//! gRPC service implementations.

use crate::generated::{
    container_service_server, image_service_server, machine_service_server, system_service_server,
    ContainerLogsRequest, ContainerState as ProtoContainerState, ContainerSummary,
    CreateContainerRequest, CreateContainerResponse, CreateMachineRequest, CreateMachineResponse,
    ExecContainerRequest, ExecMachineRequest, ExecOutput, GetInfoRequest, GetInfoResponse,
    GetVersionRequest, GetVersionResponse, InspectContainerRequest, InspectContainerResponse,
    InspectImageRequest, InspectImageResponse, InspectMachineRequest, InspectMachineResponse,
    ListContainersRequest, ListContainersResponse, ListImagesRequest, ListImagesResponse,
    ListMachinesRequest, ListMachinesResponse, LogEntry, MachineSummary, PingRequest, PingResponse,
    PullImageRequest, PullProgress, RemoveContainerRequest, RemoveContainerResponse,
    RemoveImageRequest, RemoveImageResponse, RemoveMachineRequest, RemoveMachineResponse,
    ShellInput, ShellOutput, StartContainerRequest, StartContainerResponse, StartMachineRequest,
    StartMachineResponse, StopContainerRequest, StopContainerResponse, StopMachineRequest,
    StopMachineResponse, TagImageRequest, TagImageResponse, WaitContainerRequest,
    WaitContainerResponse,
};
use arcbox_container::{ContainerConfig, ContainerId, ContainerState};
use arcbox_core::Runtime;
use arcbox_image::ImageRef;
use std::pin::Pin;
use std::sync::Arc;
use tokio_stream::Stream;
use tonic::{Request, Response, Status};

/// Container service implementation.
pub struct ContainerServiceImpl {
    runtime: Arc<Runtime>,
}

impl ContainerServiceImpl {
    /// Creates a new container service.
    #[must_use]
    pub fn new(runtime: Arc<Runtime>) -> Self {
        Self { runtime }
    }
}

#[tonic::async_trait]
impl container_service_server::ContainerService for ContainerServiceImpl {
    async fn create_container(
        &self,
        request: Request<CreateContainerRequest>,
    ) -> Result<Response<CreateContainerResponse>, Status> {
        let req = request.into_inner();

        let config = ContainerConfig {
            name: if req.name.is_empty() {
                None
            } else {
                Some(req.name)
            },
            image: req.image,
            cmd: req.cmd,
            entrypoint: req.entrypoint,
            env: req.env,
            working_dir: if req.working_dir.is_empty() {
                None
            } else {
                Some(req.working_dir)
            },
            user: if req.user.is_empty() {
                None
            } else {
                Some(req.user)
            },
            labels: req.labels,
            ..Default::default()
        };

        let id = self
            .runtime
            .container_manager()
            .create(config)
            .map_err(|e| Status::internal(e.to_string()))?;

        Ok(Response::new(CreateContainerResponse {
            id: id.to_string(),
            warnings: vec![],
        }))
    }

    async fn start_container(
        &self,
        request: Request<StartContainerRequest>,
    ) -> Result<Response<StartContainerResponse>, Status> {
        let id = ContainerId::from_string(request.into_inner().id);

        self.runtime
            .container_manager()
            .start(&id)
            .map_err(|e| Status::internal(e.to_string()))?;

        Ok(Response::new(StartContainerResponse {}))
    }

    async fn stop_container(
        &self,
        request: Request<StopContainerRequest>,
    ) -> Result<Response<StopContainerResponse>, Status> {
        let id = ContainerId::from_string(request.into_inner().id);

        self.runtime
            .container_manager()
            .stop(&id)
            .map_err(|e| Status::internal(e.to_string()))?;

        Ok(Response::new(StopContainerResponse {}))
    }

    async fn remove_container(
        &self,
        request: Request<RemoveContainerRequest>,
    ) -> Result<Response<RemoveContainerResponse>, Status> {
        let id = ContainerId::from_string(request.into_inner().id);

        self.runtime
            .container_manager()
            .remove(&id)
            .map_err(|e| Status::internal(e.to_string()))?;

        Ok(Response::new(RemoveContainerResponse {}))
    }

    async fn list_containers(
        &self,
        request: Request<ListContainersRequest>,
    ) -> Result<Response<ListContainersResponse>, Status> {
        let req = request.into_inner();

        let containers = self.runtime.container_manager().list();

        // Filter based on 'all' flag (only running if not all).
        let filtered: Vec<_> = containers
            .into_iter()
            .filter(|c| req.all || c.state == ContainerState::Running)
            .take(if req.limit > 0 {
                req.limit as usize
            } else {
                usize::MAX
            })
            .map(|c| ContainerSummary {
                id: c.id.to_string(),
                name: c.name,
                image: c.image,
                state: c.state.to_string(),
                status: format_container_status(&c.state, c.exit_code),
                created: c.created.timestamp(),
                ports: vec![],
                labels: std::collections::HashMap::new(),
            })
            .collect();

        Ok(Response::new(ListContainersResponse {
            containers: filtered,
        }))
    }

    async fn inspect_container(
        &self,
        request: Request<InspectContainerRequest>,
    ) -> Result<Response<InspectContainerResponse>, Status> {
        let id = ContainerId::from_string(request.into_inner().id);

        let container = self
            .runtime
            .container_manager()
            .get(&id)
            .ok_or_else(|| Status::not_found("container not found"))?;

        Ok(Response::new(InspectContainerResponse {
            id: container.id.to_string(),
            name: container.name,
            image: container.image,
            created: container.created.timestamp(),
            state: Some(ProtoContainerState {
                status: container.state.to_string(),
                running: container.state == ContainerState::Running,
                paused: container.state == ContainerState::Paused,
                restarting: container.state == ContainerState::Restarting,
                dead: container.state == ContainerState::Dead,
                pid: 0,
                exit_code: container.exit_code.unwrap_or(0),
                error: String::new(),
                started_at: container
                    .started_at
                    .map(|t| t.to_rfc3339())
                    .unwrap_or_default(),
                finished_at: String::new(),
            }),
            cmd: vec![],
            entrypoint: vec![],
            env: std::collections::HashMap::new(),
            working_dir: String::new(),
            mounts: vec![],
            ports: vec![],
            labels: std::collections::HashMap::new(),
        }))
    }

    async fn wait_container(
        &self,
        request: Request<WaitContainerRequest>,
    ) -> Result<Response<WaitContainerResponse>, Status> {
        let id = ContainerId::from_string(request.into_inner().id);

        // Wait for container to exit.
        // Note: This is a simplified implementation. A full implementation
        // would use async channels to wait for state changes.
        let exit_code = self.runtime.container_manager().wait(&id).unwrap_or(0);

        Ok(Response::new(WaitContainerResponse {
            status_code: i64::from(exit_code),
            error: String::new(),
        }))
    }

    type ContainerLogsStream =
        Pin<Box<dyn Stream<Item = Result<LogEntry, Status>> + Send + 'static>>;

    async fn container_logs(
        &self,
        request: Request<ContainerLogsRequest>,
    ) -> Result<Response<Self::ContainerLogsStream>, Status> {
        let req = request.into_inner();
        let container_id = ContainerId::from_string(&req.id);

        // Get container to find its machine.
        let container = self
            .runtime
            .container_manager()
            .get(&container_id)
            .ok_or_else(|| Status::not_found("container not found"))?;

        let machine_name = container
            .machine_name
            .ok_or_else(|| Status::internal("container has no machine assigned"))?;

        // Create a streaming response.
        let runtime = Arc::clone(&self.runtime);
        let follow = req.follow;
        let stdout = req.stdout;
        let stderr = req.stderr;
        let since = req.since;
        let until = req.until;
        let timestamps = req.timestamps;
        let tail = req.tail;

        let stream = async_stream::try_stream! {
            if follow {
                // Use streaming logs.
                let mut log_stream = runtime
                    .container_logs_stream(
                        &machine_name,
                        &container_id.to_string(),
                        stdout,
                        stderr,
                        since,
                        until,
                        timestamps,
                        tail,
                    )
                    .await
                    .map_err(|e| Status::internal(e.to_string()))?;

                use tokio_stream::StreamExt;
                while let Some(result) = log_stream.next().await {
                    match result {
                        Ok(entry) => {
                            yield LogEntry {
                                timestamp: entry.timestamp,
                                stream: entry.stream,
                                data: entry.data,
                            };
                        }
                        Err(e) => {
                            Err(Status::internal(e.to_string()))?;
                        }
                    }
                }
            } else {
                // Get logs once.
                let entry = runtime
                    .container_logs(
                        &machine_name,
                        &container_id.to_string(),
                        false,
                        stdout,
                        stderr,
                        since,
                        until,
                        timestamps,
                        tail,
                    )
                    .await
                    .map_err(|e| Status::internal(e.to_string()))?;

                yield LogEntry {
                    timestamp: entry.timestamp,
                    stream: entry.stream,
                    data: entry.data,
                };
            }
        };

        Ok(Response::new(Box::pin(stream)))
    }

    type ExecContainerStream =
        Pin<Box<dyn Stream<Item = Result<ExecOutput, Status>> + Send + 'static>>;

    async fn exec_container(
        &self,
        request: Request<ExecContainerRequest>,
    ) -> Result<Response<Self::ExecContainerStream>, Status> {
        let req = request.into_inner();
        let container_id = ContainerId::from_string(&req.id);

        // Get container to find its machine.
        let container = self
            .runtime
            .container_manager()
            .get(&container_id)
            .ok_or_else(|| Status::not_found("container not found"))?;

        let machine_name = container
            .machine_name
            .ok_or_else(|| Status::internal("container has no machine assigned"))?;

        // Get CID for the machine.
        let cid = self
            .runtime
            .machine_manager()
            .get_cid(&machine_name)
            .ok_or_else(|| Status::internal("machine has no CID"))?;

        // Build exec request for agent.
        let agent_req = arcbox_protocol::agent::ExecRequest {
            container_id: req.id.clone(),
            cmd: req.cmd,
            env: req.env,
            working_dir: req.working_dir,
            user: req.user,
            tty: req.tty,
        };

        let agent_pool = Arc::clone(self.runtime.agent_pool());

        let stream = async_stream::try_stream! {
            let agent = agent_pool.get(cid).await;
            let mut agent = agent.write().await;

            let output = agent
                .exec(agent_req)
                .await
                .map_err(|e| Status::internal(e.to_string()))?;

            // Yield output data if present.
            if !output.data.is_empty() {
                yield ExecOutput {
                    stream: output.stream.clone(),
                    data: output.data.clone(),
                    exit_code: 0,
                    done: false,
                };
            }

            // Final message with exit code.
            yield ExecOutput {
                stream: String::new(),
                data: Vec::new(),
                exit_code: output.exit_code,
                done: true,
            };
        };

        Ok(Response::new(Box::pin(stream)))
    }
}

/// Machine service implementation.
pub struct MachineServiceImpl {
    runtime: Arc<Runtime>,
}

impl MachineServiceImpl {
    /// Creates a new machine service.
    #[must_use]
    pub fn new(runtime: Arc<Runtime>) -> Self {
        Self { runtime }
    }
}

#[tonic::async_trait]
impl machine_service_server::MachineService for MachineServiceImpl {
    async fn create_machine(
        &self,
        request: Request<CreateMachineRequest>,
    ) -> Result<Response<CreateMachineResponse>, Status> {
        let req = request.into_inner();

        // Convert bytes to MB for internal config.
        let memory_mb = req.memory / (1024 * 1024);
        let disk_gb = req.disk_size / (1024 * 1024 * 1024);

        let config = arcbox_core::machine::MachineConfig {
            name: req.name.clone(),
            cpus: req.cpus,
            memory_mb,
            disk_gb,
        };

        self.runtime
            .machine_manager()
            .create(config)
            .map_err(|e| Status::internal(e.to_string()))?;

        Ok(Response::new(CreateMachineResponse { id: req.name }))
    }

    async fn start_machine(
        &self,
        request: Request<StartMachineRequest>,
    ) -> Result<Response<StartMachineResponse>, Status> {
        let id = request.into_inner().id;

        self.runtime
            .machine_manager()
            .start(&id)
            .map_err(|e| Status::internal(e.to_string()))?;

        Ok(Response::new(StartMachineResponse {}))
    }

    async fn stop_machine(
        &self,
        request: Request<StopMachineRequest>,
    ) -> Result<Response<StopMachineResponse>, Status> {
        let id = request.into_inner().id;

        self.runtime
            .machine_manager()
            .stop(&id)
            .map_err(|e| Status::internal(e.to_string()))?;

        Ok(Response::new(StopMachineResponse {}))
    }

    async fn remove_machine(
        &self,
        request: Request<RemoveMachineRequest>,
    ) -> Result<Response<RemoveMachineResponse>, Status> {
        let req = request.into_inner();

        self.runtime
            .machine_manager()
            .remove(&req.id, req.force)
            .map_err(|e| Status::internal(e.to_string()))?;

        Ok(Response::new(RemoveMachineResponse {}))
    }

    async fn list_machines(
        &self,
        _request: Request<ListMachinesRequest>,
    ) -> Result<Response<ListMachinesResponse>, Status> {
        let machines = self.runtime.machine_manager().list();

        let summaries: Vec<_> = machines
            .into_iter()
            .map(|m| MachineSummary {
                id: m.name.clone(),
                name: m.name,
                state: format!("{:?}", m.state).to_lowercase(),
                cpus: m.cpus,
                memory: m.memory_mb * 1024 * 1024,
                created: 0, // TODO: Add created timestamp to MachineInfo
            })
            .collect();

        Ok(Response::new(ListMachinesResponse {
            machines: summaries,
        }))
    }

    async fn inspect_machine(
        &self,
        request: Request<InspectMachineRequest>,
    ) -> Result<Response<InspectMachineResponse>, Status> {
        let id = request.into_inner().id;

        let machine = self
            .runtime
            .machine_manager()
            .get(&id)
            .ok_or_else(|| Status::not_found("machine not found"))?;

        Ok(Response::new(InspectMachineResponse {
            id: machine.name.clone(),
            name: machine.name,
            state: format!("{:?}", machine.state).to_lowercase(),
            cpus: machine.cpus,
            memory: machine.memory_mb * 1024 * 1024,
            disk_size: machine.disk_gb * 1024 * 1024 * 1024,
            created: 0, // TODO: Add created timestamp
            kernel: String::new(),
            initrd: String::new(),
            cmdline: String::new(),
            cid: 0, // TODO: Add CID for vsock
        }))
    }

    type ExecMachineStream =
        Pin<Box<dyn Stream<Item = Result<ExecOutput, Status>> + Send + 'static>>;

    async fn exec_machine(
        &self,
        request: Request<ExecMachineRequest>,
    ) -> Result<Response<Self::ExecMachineStream>, Status> {
        let req = request.into_inner();
        let machine_name = req.id;

        // Get CID for the machine.
        let cid = self
            .runtime
            .machine_manager()
            .get_cid(&machine_name)
            .ok_or_else(|| Status::not_found("machine not found or not running"))?;

        // Build exec request for agent (empty container_id for VM-level exec).
        let agent_req = arcbox_protocol::agent::ExecRequest {
            container_id: String::new(), // Empty = run in VM namespace, not in a container
            cmd: req.cmd,
            env: req.env,
            working_dir: req.working_dir,
            user: req.user,
            tty: req.tty,
        };

        let agent_pool = Arc::clone(self.runtime.agent_pool());

        let stream = async_stream::try_stream! {
            let agent = agent_pool.get(cid).await;
            let mut agent = agent.write().await;

            let output = agent
                .exec(agent_req)
                .await
                .map_err(|e| Status::internal(e.to_string()))?;

            // Yield output data if present.
            if !output.data.is_empty() {
                yield ExecOutput {
                    stream: output.stream.clone(),
                    data: output.data.clone(),
                    exit_code: 0,
                    done: false,
                };
            }

            // Final message with exit code.
            yield ExecOutput {
                stream: String::new(),
                data: Vec::new(),
                exit_code: output.exit_code,
                done: true,
            };
        };

        Ok(Response::new(Box::pin(stream)))
    }

    type ShellMachineStream =
        Pin<Box<dyn Stream<Item = Result<ShellOutput, Status>> + Send + 'static>>;

    async fn shell_machine(
        &self,
        request: Request<tonic::Streaming<ShellInput>>,
    ) -> Result<Response<Self::ShellMachineStream>, Status> {
        let machine_name = {
            // Extract machine name from metadata (the client should send it).
            request
                .metadata()
                .get("machine-id")
                .and_then(|v| v.to_str().ok())
                .map(String::from)
                .ok_or_else(|| Status::invalid_argument("missing machine-id header"))?
        };

        // Get CID for the machine.
        let cid = self
            .runtime
            .machine_manager()
            .get_cid(&machine_name)
            .ok_or_else(|| Status::not_found("machine not found or not running"))?;

        let agent_pool = Arc::clone(self.runtime.agent_pool());
        let mut input_stream = request.into_inner();

        let stream = async_stream::try_stream! {
            let agent = agent_pool.get(cid).await;
            let mut agent = agent.write().await;

            // Start a shell session - use exec with /bin/sh.
            let shell_req = arcbox_protocol::agent::ExecRequest {
                container_id: String::new(),
                cmd: vec!["/bin/sh".to_string()],
                env: std::collections::HashMap::new(),
                working_dir: String::new(),
                user: String::new(),
                tty: true,
            };

            let output = agent
                .exec(shell_req)
                .await
                .map_err(|e| Status::internal(e.to_string()))?;

            // Yield initial output.
            yield ShellOutput {
                data: output.data,
                exit_code: output.exit_code,
                done: output.done,
            };

            // Process input from client (simplified - in a real implementation,
            // we'd need bidirectional streaming to the agent).
            use tokio_stream::StreamExt;
            while let Some(result) = input_stream.next().await {
                match result {
                    Ok(_input) => {
                        // In a full implementation, we'd send input to the agent
                        // and yield output back. For now, we just acknowledge.
                        // This requires a more complex bidirectional protocol with the agent.
                    }
                    Err(e) => {
                        Err(Status::internal(format!("input stream error: {}", e)))?;
                    }
                }
            }

            // Final output when stream ends.
            yield ShellOutput {
                data: Vec::new(),
                exit_code: 0,
                done: true,
            };
        };

        Ok(Response::new(Box::pin(stream)))
    }
}

/// Image service implementation.
pub struct ImageServiceImpl {
    runtime: Arc<Runtime>,
}

impl ImageServiceImpl {
    /// Creates a new image service.
    #[must_use]
    pub fn new(runtime: Arc<Runtime>) -> Self {
        Self { runtime }
    }
}

#[tonic::async_trait]
impl image_service_server::ImageService for ImageServiceImpl {
    type PullImageStream =
        Pin<Box<dyn Stream<Item = Result<PullProgress, Status>> + Send + 'static>>;

    async fn pull_image(
        &self,
        request: Request<PullImageRequest>,
    ) -> Result<Response<Self::PullImageStream>, Status> {
        let _req = request.into_inner();

        // TODO: Implement actual image pull with progress streaming.
        let stream = async_stream::stream! {
            yield Ok(PullProgress {
                status: "Pulling image...".to_string(),
                id: String::new(),
                progress: String::new(),
                error: String::new(),
            });
            yield Ok(PullProgress {
                status: "Pull complete".to_string(),
                id: String::new(),
                progress: String::new(),
                error: String::new(),
            });
        };

        Ok(Response::new(Box::pin(stream)))
    }

    async fn remove_image(
        &self,
        request: Request<RemoveImageRequest>,
    ) -> Result<Response<RemoveImageResponse>, Status> {
        let req = request.into_inner();

        let image_ref = ImageRef::parse(&req.reference)
            .ok_or_else(|| Status::invalid_argument("invalid image reference"))?;

        self.runtime
            .image_store()
            .remove(&image_ref)
            .map_err(|e| Status::internal(e.to_string()))?;

        Ok(Response::new(RemoveImageResponse {
            untagged: vec![],
            deleted: vec![req.reference],
        }))
    }

    async fn list_images(
        &self,
        _request: Request<ListImagesRequest>,
    ) -> Result<Response<ListImagesResponse>, Status> {
        let images = self.runtime.image_store().list();

        let summaries: Vec<_> = images
            .into_iter()
            .map(|img| crate::generated::ImageSummary {
                id: img.id.clone(),
                repo_tags: vec![img.reference.full_name()],
                repo_digests: vec![],
                created: img.created.timestamp(),
                size: img.size as i64,
                labels: std::collections::HashMap::new(),
            })
            .collect();

        Ok(Response::new(ListImagesResponse { images: summaries }))
    }

    async fn inspect_image(
        &self,
        request: Request<InspectImageRequest>,
    ) -> Result<Response<InspectImageResponse>, Status> {
        let req = request.into_inner();

        let image_ref = ImageRef::parse(&req.reference)
            .ok_or_else(|| Status::invalid_argument("invalid image reference"))?;

        let image = self
            .runtime
            .image_store()
            .get(&image_ref)
            .ok_or_else(|| Status::not_found("image not found"))?;

        Ok(Response::new(InspectImageResponse {
            id: image.id.clone(),
            repo_tags: vec![image.reference.full_name()],
            repo_digests: vec![],
            parent: String::new(),
            comment: String::new(),
            created: image.created.timestamp(),
            author: String::new(),
            architecture: String::new(),
            os: "linux".to_string(),
            size: image.size as i64,
            cmd: vec![],
            entrypoint: vec![],
            env: std::collections::HashMap::new(),
            working_dir: String::new(),
            labels: std::collections::HashMap::new(),
        }))
    }

    async fn tag_image(
        &self,
        request: Request<TagImageRequest>,
    ) -> Result<Response<TagImageResponse>, Status> {
        let req = request.into_inner();

        let source = ImageRef::parse(&req.source)
            .ok_or_else(|| Status::invalid_argument("invalid source reference"))?;

        // Construct target from repo:tag
        let target_str = if req.tag.is_empty() {
            format!("{}:latest", req.repo)
        } else {
            format!("{}:{}", req.repo, req.tag)
        };
        let target = ImageRef::parse(&target_str)
            .ok_or_else(|| Status::invalid_argument("invalid target reference"))?;

        self.runtime
            .image_store()
            .tag(&source, &target)
            .map_err(|e| Status::internal(e.to_string()))?;

        Ok(Response::new(TagImageResponse {}))
    }
}

/// System service implementation.
pub struct SystemServiceImpl {
    runtime: Arc<Runtime>,
}

impl SystemServiceImpl {
    /// Creates a new system service.
    #[must_use]
    pub fn new(runtime: Arc<Runtime>) -> Self {
        Self { runtime }
    }
}

#[tonic::async_trait]
impl system_service_server::SystemService for SystemServiceImpl {
    async fn get_info(
        &self,
        _request: Request<GetInfoRequest>,
    ) -> Result<Response<GetInfoResponse>, Status> {
        let containers = self.runtime.container_manager().list();
        let images = self.runtime.image_store().list();
        let machines = self.runtime.machine_manager().list();

        let running = containers
            .iter()
            .filter(|c| c.state == ContainerState::Running)
            .count() as i64;
        let paused = containers
            .iter()
            .filter(|c| c.state == ContainerState::Paused)
            .count() as i64;
        let stopped = containers.len() as i64 - running - paused;

        let machines_running = machines
            .iter()
            .filter(|m| m.state == arcbox_core::machine::MachineState::Running)
            .count() as i64;

        Ok(Response::new(GetInfoResponse {
            containers: containers.len() as i64,
            containers_running: running,
            containers_paused: paused,
            containers_stopped: stopped,
            images: images.len() as i64,
            machines: machines.len() as i64,
            machines_running,
            server_version: env!("CARGO_PKG_VERSION").to_string(),
            os: std::env::consts::OS.to_string(),
            arch: std::env::consts::ARCH.to_string(),
            mem_total: total_memory(),
            ncpu: num_cpus(),
            data_dir: self
                .runtime
                .config()
                .data_dir
                .to_string_lossy()
                .to_string(),
        }))
    }

    async fn get_version(
        &self,
        _request: Request<GetVersionRequest>,
    ) -> Result<Response<GetVersionResponse>, Status> {
        Ok(Response::new(GetVersionResponse {
            version: env!("CARGO_PKG_VERSION").to_string(),
            api_version: "1.0.0".to_string(),
            git_commit: option_env!("ARCBOX_GIT_COMMIT")
                .unwrap_or("unknown")
                .to_string(),
            build_time: option_env!("ARCBOX_BUILD_TIME")
                .unwrap_or("unknown")
                .to_string(),
            os: std::env::consts::OS.to_string(),
            arch: std::env::consts::ARCH.to_string(),
        }))
    }

    async fn ping(
        &self,
        _request: Request<PingRequest>,
    ) -> Result<Response<PingResponse>, Status> {
        Ok(Response::new(PingResponse {
            api_version: "1.0.0".to_string(),
        }))
    }
}

/// Formats a container status string.
fn format_container_status(state: &ContainerState, exit_code: Option<i32>) -> String {
    match state {
        ContainerState::Created => "Created".to_string(),
        ContainerState::Running => "Up".to_string(),
        ContainerState::Paused => "Paused".to_string(),
        ContainerState::Restarting => "Restarting".to_string(),
        ContainerState::Exited => {
            format!("Exited ({})", exit_code.unwrap_or(0))
        }
        ContainerState::Removing => "Removing".to_string(),
        ContainerState::Dead => "Dead".to_string(),
    }
}

/// Returns the number of CPUs.
fn num_cpus() -> i32 {
    std::thread::available_parallelism()
        .map(|n| n.get() as i32)
        .unwrap_or(1)
}

/// Returns total system memory in bytes.
fn total_memory() -> i64 {
    #[cfg(target_os = "macos")]
    {
        let mut size: u64 = 0;
        let mut len = std::mem::size_of::<u64>();
        let mut mib = [libc::CTL_HW, libc::HW_MEMSIZE];

        // SAFETY: sysctl is called with valid parameters.
        let ret = unsafe {
            libc::sysctl(
                mib.as_mut_ptr(),
                2,
                std::ptr::addr_of_mut!(size).cast::<libc::c_void>(),
                &mut len,
                std::ptr::null_mut(),
                0,
            )
        };

        if ret == 0 {
            size as i64
        } else {
            0
        }
    }

    #[cfg(target_os = "linux")]
    {
        use std::fs;

        fs::read_to_string("/proc/meminfo")
            .ok()
            .and_then(|content| {
                content
                    .lines()
                    .find(|line| line.starts_with("MemTotal:"))
                    .and_then(|line| {
                        line.split_whitespace()
                            .nth(1)
                            .and_then(|s| s.parse::<i64>().ok())
                    })
            })
            .map(|kb| kb * 1024)
            .unwrap_or(0)
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        0
    }
}