fundaia 0.26.0

Command line for the Fundaia deployment platform: projects, services, variables, deployments, logs and metrics
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
//! Everything that changes something.
//!
//! Each of these prints one line saying what happened, and that line names the
//! thing it happened to. `deploy` is not here — it is long-lived enough to have
//! a view of its own.

use anyhow::{bail, Context, Result};
use owo_colors::OwoColorize;

use crate::api::client::{ApiClient, ApiError};
use crate::api::models::{
    AgentSetup, AgentSetupPatch, CanvasPlacement, ClaudeCodeSetupRequest, NewService, Template,
    TemplatesPage,
};
use crate::commands::dotenv;
use crate::output::{self, Format};
use crate::render::table::truncate;
use crate::render::theme;

/// Emails the repository's owner a link that grants read access.
///
/// The address is the one thing that cannot be worked out: GitHub publishes one
/// for almost no account, so `--email` is what unblocks the usual case and
/// omitting it reuses whatever this space already used for that account.
///
/// The link is printed because copying it is what saves the flow when delivery is
/// slow or the address had a typo — and it is said out loud that it is a
/// credential, so nobody pastes it into a commit.
pub async fn request_repository_access(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    email: Option<&str>,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;
    let sent = client.request_repository_access(&service.id, email).await?;

    if format.is_json() {
        output::emit(&sent);
        return Ok(());
    }

    println!(
        "  enlace enviado a {} para leer {}",
        sent.request
            .email
            .clone()
            .unwrap_or_else(|| format!("@{}", sent.request.owner_login))
            .style(theme::strong()),
        sent.request.repo_full_name.style(theme::strong())
    );
    println!("  {}", sent.approve_url.style(theme::muted()));
    println!();
    println!(
        "  {}",
        "ese enlace concede el acceso: trátalo como una credencial. El servicio se despliega solo en cuanto lo autorice."
            .style(theme::muted())
    );
    Ok(())
}

pub async fn set_variable(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    key: &str,
    value: &str,
    secret: bool,
    sealed: bool,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    client
        .set_variable(&service.id, key, value, secret, sealed)
        .await?;

    println!(
        "  {} {} en {}{}",
        theme::CHECK.style(theme::success()),
        key.style(theme::strong()),
        service.name.style(theme::strong()),
        match (sealed, secret) {
            (true, _) => " (sellada)",
            (false, true) => " (secreto)",
            _ => "",
        },
    );
    if sealed {
        println!(
            "  {}",
            "Su valor ya no se puede leer ni cambiar en ningún sitio. Solo borrarla."
                .style(theme::muted()),
        );
    }
    println!(
        "  {}",
        "El servicio se reinicia para recogerla. Dormido, la verá al despertar."
            .style(theme::muted()),
    );

    Ok(())
}

/// Seals an existing variable.
///
/// The key has to be typed back, the same way deleting a service asks for its
/// name. This cannot be undone and it is one letter away from `set` in a shell
/// history — a flag on its own is a guard people learn to type without reading.
pub async fn seal_variable(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    key: &str,
    confirmation: Option<&str>,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let variables = client.variables(&service.id).await?;
    let Some(variable) = variables.into_iter().find(|variable| variable.key == key) else {
        bail!(
            "`{}` no define ninguna variable llamada `{key}`",
            service.name
        );
    };

    if variable.is_sealed() {
        println!(
            "  {} {} ya estaba sellada",
            theme::CHECK.style(theme::success()),
            key.style(theme::strong())
        );
        return Ok(());
    }

    if variable.kind == "reference" {
        bail!("`{key}` es una referencia: no guarda ningún valor propio. Sella la variable a la que apunta.");
    }

    if confirmation != Some(key) {
        bail!(
            "escribe `--confirm {key}` para sellarla: dejará de poder verse y de poder cambiarse, y no se deshace"
        );
    }

    client.seal_variable(&variable.id).await?;

    println!(
        "  {} {} sellada en {}",
        theme::CHECK.style(theme::success()),
        key.style(theme::strong()),
        service.name.style(theme::strong()),
    );
    println!(
        "  {}",
        "El contenedor la sigue recibiendo. Nadie más vuelve a verla.".style(theme::muted()),
    );

    Ok(())
}

pub async fn unset_variable(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    key: &str,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let variables = client.variables(&service.id).await?;
    let Some(variable) = variables.into_iter().find(|variable| variable.key == key) else {
        bail!(
            "`{}` no define ninguna variable llamada `{key}`",
            service.name
        );
    };

    client.remove_variable(&variable.id).await?;
    println!(
        "  {} {} eliminada",
        theme::CHECK.style(theme::success()),
        key.style(theme::strong())
    );

    Ok(())
}

/// Wires one service to another, letting the server decide what that means.
///
/// The CLI never invents the variables. Which keys a Postgres hands over is a
/// rule that lives in `domain/connectors.ts`, and duplicating it here would be
/// two implementations of one convention, drifting.
pub async fn connect(
    client: &ApiClient,
    project_reference: &str,
    consumer_reference: &str,
    provider_reference: &str,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let consumer = client.find_service(&project.id, consumer_reference).await?;
    let provider = client.find_service(&project.id, provider_reference).await?;

    let connection = client.connect(&consumer.id, &provider.id).await?;

    println!(
        "  {} {} {} {}",
        theme::CHECK.style(theme::success()),
        consumer.name.style(theme::strong()),
        theme::ARROW.style(theme::muted()),
        connection.provider_name.style(theme::strong()),
    );
    println!("  {}", connection.summary.style(theme::muted()));

    for key in &connection.keys {
        println!("    {} {}", "+".style(theme::success()), key);
    }

    Ok(())
}

pub async fn candidates(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;
    let candidates = client.candidates(&service.id).await?;

    if format.is_json() {
        output::emit(&candidates);
        return Ok(());
    }

    if candidates.is_empty() {
        println!("No hay nada a lo que `{}` pueda conectarse.", service.name);
        return Ok(());
    }

    for candidate in &candidates {
        println!(
            "  {} {}",
            candidate.name.style(theme::strong()),
            candidate.summary.style(theme::muted()),
        );
    }

    Ok(())
}

pub async fn add_domain(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    host: Option<&str>,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let domain = client.add_domain(&service.id, host).await?;

    println!(
        "  {} {}",
        theme::CHECK.style(theme::success()),
        domain.url.style(theme::accent())
    );

    if let Some(instructions) = &domain.dns_instructions {
        println!("  {} {}", "!".style(theme::warning()), instructions);
    }

    Ok(())
}

pub async fn remove_domain(client: &ApiClient, domain_id: &str) -> Result<()> {
    client.remove_domain(domain_id).await?;
    println!(
        "  {} Dominio eliminado",
        theme::CHECK.style(theme::success())
    );
    Ok(())
}

pub async fn stop(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    client.stop(&service.id).await?;
    println!(
        "  {} {} parado — despertará con la siguiente petición",
        theme::CHECK.style(theme::success()),
        service.name.style(theme::strong()),
    );

    Ok(())
}

/// What `fundaia new` was asked for, before any of it is resolved.
///
/// A struct rather than eight parameters, and not only to satisfy a lint: the
/// three sources are mutually exclusive and the check that says so reads far
/// better against one value than against a signature nobody can call without
/// consulting it.
pub struct ServiceRequest<'a> {
    pub project: &'a str,
    pub name: &'a str,
    pub repo: Option<&'a str>,
    pub image: Option<&'a str>,
    /// A component from the catalogue: `postgres-16`, `bucket`, `claude-code`.
    pub template: Option<&'a str>,
    /// Build from code uploaded by hand, with no repository behind it.
    pub upload: bool,
    pub branch: &'a str,
    /// Services it should be able to talk to, by whatever name a person types.
    pub connect_to: &'a [String],
    /// Create it without starting it. Creating a service deploys it otherwise.
    pub no_deploy: bool,
    /// For `claude-code`: the token `claude setup-token` prints. Left out, it
    /// is asked for in the terminal — unless the catalogue says this account
    /// may leave it out, which is the instance owner and nobody else.
    pub setup_token: Option<&'a str>,
    /// For `claude-code`: which model. The server's default when absent.
    pub model: Option<&'a str>,
    /// For `claude-code`: how hard it thinks. The server's default when absent.
    pub effort: Option<&'a str>,
}

/// Creates a service, and optionally wires it up in the same breath.
///
/// `--connect-to` accepts the names a person can see, resolved here rather than
/// on the server, because the server keys on ids and a CLI that demanded ids
/// would be a CLI nobody types twice.
pub async fn create_service(
    client: &ApiClient,
    request: ServiceRequest<'_>,
    format: Format,
) -> Result<()> {
    let project = client.find_project(request.project).await?;

    let source_kind = match (
        request.repo,
        request.image,
        request.template,
        request.upload,
    ) {
        (Some(_), None, None, false) => "github",
        (None, Some(_), None, false) => "image",
        (None, None, Some(_), false) => "template",
        (None, None, None, true) => "upload",
        (None, None, None, false) => {
            bail!("say where it comes from: --repo, --image, --template or --upload")
        }
        _ => bail!("--repo, --image, --template and --upload are alternatives, not a set"),
    };

    let mut providers = Vec::new();
    for reference in request.connect_to {
        providers.push(client.find_service(&project.id, reference).await?.id);
    }

    // Asked before anything is sent, not after the server says no: a person
    // at a terminal can paste what the component needs right here.
    let setup_token = match (request.setup_token, request.template) {
        (Some(token), _) => Some(token.to_owned()),
        (None, Some(key)) => ask_setup_token(client, key, format).await?,
        (None, None) => None,
    };

    let draft = NewService {
        name: request.name.to_owned(),
        source_kind: source_kind.to_owned(),
        repo_full_name: request.repo.map(str::to_owned),
        branch: request.repo.map(|_| request.branch.to_owned()),
        image: request.image.map(str::to_owned),
        template_key: request.template.map(str::to_owned),
        // Every catalogue component is created as `database`, Claude Code
        // included, because that is what the web sends and two clients that
        // disagree produce two kinds of the same service. Nothing keys on it
        // anyway: a connector recognises its provider by the template key.
        kind: request.template.map(|_| "database".to_owned()),
        connect_to: providers,
        // Sent only to say no. Omitting it lets the server decide, which is what
        // keeps this working against an instance that predates the flag.
        deploy_now: request.no_deploy.then_some(false),
        // Only when something was said: an older server ignores the key, and a
        // newer one reads an absent field as its default.
        claude: (setup_token.is_some() || request.model.is_some() || request.effort.is_some())
            .then(|| ClaudeCodeSetupRequest {
                setup_token,
                model: request.model.map(str::to_owned),
                effort: request.effort.map(str::to_owned),
            }),
    };

    if let Err(error) = client.create_service(&project.id, &draft).await {
        return Err(match request.template {
            Some(key) => explain_template_refusal(error, key),
            None => error,
        });
    }

    println!(
        "  {} {} creado en {}",
        theme::CHECK.style(theme::success()),
        request.name.style(theme::strong()),
        project.name.style(theme::strong()),
    );

    if !request.connect_to.is_empty() {
        println!(
            "  {} conectado a {}",
            theme::ARROW.style(theme::muted()),
            request.connect_to.join(", "),
        );
    }

    // Said out loud because it happens without being asked for. Somebody who
    // does not know a deployment started would read the next `fundaia service`
    // as the service breaking on its own.
    println!(
        "  {} {}",
        theme::ARROW.style(theme::muted()),
        if request.upload {
            /* Nothing to deploy yet, whatever `--no-deploy` said: this service
             * has no code until an archive arrives, and the archive arriving is
             * what starts its first deployment. */
            format!(
                "sin código todavía — `fundaia up {} {}` desde el directorio del proyecto",
                project.name, request.name
            )
        } else if request.no_deploy {
            format!(
                "sin desplegar — `fundaia deploy {} {}` cuando lo quieras",
                project.name, request.name
            )
        } else {
            // Not `deploy`, which would start a second one on top of this.
            format!("desplegando — `fundaia watch {}` para verlo", project.name)
        },
    );

    Ok(())
}

/// Says what a `not_found` on a template can mean, because the server will not.
///
/// A component an instance keeps for its owner answers exactly like a key that
/// does not exist. That is deliberate on the server's side: which components
/// an instance offers somebody else is not a stranger's business. It makes a
/// good answer and a useless message, so the tool names both readings rather
/// than printing a 404 nobody can interpret. Nothing in the catalogue is
/// owner-only today — Claude Code stopped being so when each component got a
/// token of its own — but an instance may still say no, and this still reads it.
///
/// The original stays in the chain as the cause, and the exit code is unchanged:
/// this reworded a failure, it did not forgive one.
fn explain_template_refusal(error: anyhow::Error, key: &str) -> anyhow::Error {
    let Some(api) = error.downcast_ref::<ApiError>() else {
        return error;
    };

    if api.code == "not_found" {
        return error.context(format!(
            "el componente `{key}` no está disponible: o no existe en esta instancia, \
             o esta cuenta no puede añadirlo — `fundaia templates` lista los que \
             sí puede crear"
        ));
    }

    // The one validation a component can fail before it exists: the token it
    // runs on. Said in the terminal's own words, with the flag that fixes it.
    if api.code == "validation_failed" && api.message.contains("token") {
        return error.context(format!(
            "el componente `{key}` gasta tu propia suscripción de Claude: pásale el token \
             que imprime `claude setup-token` con --setup-token"
        ));
    }

    error
}

/// The token a component that runs on somebody's subscription cannot be
/// created without, asked for at the keyboard.
///
/// Only when the catalogue says this account has to give one — the instance
/// owner is never asked, because their components run on the server's own —
/// and only when there is a keyboard: `--json`, a pipe or a script gets the
/// sentence naming the flag instead of a prompt it cannot answer. Read with
/// the echo off, the way `claude setup-token` was itself typed: a credential
/// that lasts a year has no business in a scrollback.
async fn ask_setup_token(client: &ApiClient, key: &str, format: Format) -> Result<Option<String>> {
    let page = client.templates().await?;
    let Some(setup) = page
        .templates
        .iter()
        .find(|template| template.key == key)
        .and_then(|template| template.setup.as_ref())
    else {
        return Ok(None);
    };
    if setup.token_optional {
        return Ok(None);
    }

    let interactive = !format.is_json() && std::io::IsTerminal::is_terminal(&std::io::stdin());
    if !interactive {
        bail!(
            "el componente `{key}` gasta tu propia suscripción de Claude: pásale el token \
             que imprime `claude setup-token` con --setup-token"
        );
    }

    eprintln!(
        "  El componente {} gasta tu propia suscripción de Claude.",
        key.style(theme::strong()),
    );
    eprintln!(
        "  {}",
        "Genera el token en tu ordenador con `claude setup-token` y pégalo aquí; no se ve al escribir."
            .style(theme::muted()),
    );
    eprint!("  Setup token: ");
    let token = rpassword::read_password().context("no se pudo leer el token del teclado")?;
    let token = token.trim().to_owned();
    if token.is_empty() {
        bail!("sin token no se puede crear el componente `{key}`: pásalo con --setup-token o vuelve a intentarlo");
    }

    Ok(Some(token))
}

/// Shows what a Claude Code component runs on, or changes it.
///
/// One command for both, decided by whether anything was passed: the shape
/// `fundaia settings` already has. With nothing to change it reads; with
/// something it writes and then prints what the server says it is now, which
/// is the same answer either way. The token is never printed, in either mode —
/// only whether there is one.
pub async fn agent(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    patch: AgentSetupPatch,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let changed = !patch.is_empty();
    let setup = if changed {
        client.configure_agent(&service.id, &patch).await?
    } else {
        client.agent_setup(&service.id).await?
    };

    if format.is_json() {
        output::emit(&setup);
        return Ok(());
    }

    if changed {
        println!(
            "  {} Agente {} configurado — el contenedor se reinicia para recogerlo",
            theme::CHECK.style(theme::success()),
            service.name.style(theme::strong()),
        );
    } else {
        println!();
        println!("  {}", service.name.style(theme::strong()));
    }

    print_agent_setup(&setup);
    Ok(())
}

/// The three facts, one per line, with the catalogue's word beside each id.
fn print_agent_setup(setup: &AgentSetup) {
    println!(
        "  {} {}{}",
        "modelo".style(theme::muted()),
        setup.model.style(theme::accent()),
        label_of(&setup.models, &setup.model),
    );
    println!(
        "  {} {}{}",
        "esfuerzo".style(theme::muted()),
        setup.effort.style(theme::accent()),
        label_of(&setup.efforts, &setup.effort),
    );
    println!(
        "  {} {}",
        "token".style(theme::muted()),
        credential_word(setup.credential.configured, setup.credential.sealed),
    );
}

/// ` · Sonnet 5`, or nothing for an id the catalogue does not describe.
fn label_of(options: &[crate::api::models::ClaudeOption], id: &str) -> String {
    options
        .iter()
        .find(|one| one.id == id)
        .map(|one| format!(" · {}", one.label))
        .unwrap_or_default()
}

/// What to say about a credential, without ever saying what it is.
pub fn credential_word(configured: bool, sealed: bool) -> &'static str {
    match (configured, sealed) {
        (false, _) => "ninguno — cada prompt fallará hasta que pegues uno",
        (true, true) => "el del servidor, sellado: el contenedor lo recibe y nadie lo lee",
        (true, false) => "propio, configurado",
    }
}

/// The ids, comma-separated, with the default marked: `low, medium, high*, …`.
pub fn ids_of(options: &[crate::api::models::ClaudeOption], default: &str) -> String {
    options
        .iter()
        .map(|one| {
            if one.id == default {
                format!("{}*", one.id)
            } else {
                one.id.clone()
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// The entries of one category, in the order the server sent them.
///
/// A function rather than a closure inside the printing loop, so the grouping
/// can be tested without a server: it is the one piece of that command with a
/// rule in it, and the rule is "the server decided, do not re-sort".
fn entries_of<'a>(page: &'a TemplatesPage, category: &str) -> Vec<&'a Template> {
    page.templates
        .iter()
        .filter(|template| template.category == category)
        .collect()
}

/// Anything grouped under a category this build does not know about.
///
/// Printing them beats hiding a component because the CLI is older than the
/// server — which is the ordinary case for a tool that updates itself daily.
fn ungrouped(page: &TemplatesPage) -> Vec<&Template> {
    let known: Vec<&str> = page.categories.iter().map(|one| one.id.as_str()).collect();
    page.templates
        .iter()
        .filter(|template| !known.contains(&template.category.as_str()))
        .collect()
}

pub async fn templates(client: &ApiClient, format: Format) -> Result<()> {
    let page = client.templates().await?;

    if format.is_json() {
        output::emit(&page);
        return Ok(());
    }

    /*
     * Grouped the way the server groups it, not sorted here.
     *
     * The categories come down with the entries precisely so this and the
     * canvas present one catalogue rather than two, which is the same argument
     * the deployment pipeline makes for being derived on the server.
     */
    for category in &page.categories {
        let entries = entries_of(&page, &category.id);
        if entries.is_empty() {
            continue;
        }

        println!("\n{}", category.label.style(theme::strong()));
        for template in entries {
            println!(
                "  {}  {}",
                template.key.style(theme::accent()),
                template.display_name,
            );
            if !template.summary.is_empty() {
                println!("      {}", template.summary.style(theme::muted()));
            }
            // What this one asks for on top of its key, so `fundaia new` can be
            // typed without a round trip to the documentation.
            if let Some(setup) = &template.setup {
                println!(
                    "      {} {}",
                    "--model".style(theme::muted()),
                    ids_of(&setup.models, &setup.default_model),
                );
                println!(
                    "      {} {}",
                    "--effort".style(theme::muted()),
                    ids_of(&setup.efforts, &setup.default_effort),
                );
                println!(
                    "      {} {}",
                    "--setup-token".style(theme::muted()),
                    if setup.token_optional {
                        "no hace falta: tus componentes usan el del servidor"
                    } else {
                        "obligatorio: lo imprime `claude setup-token`"
                    }
                    .style(theme::muted()),
                );
            }
        }
    }

    let orphans = ungrouped(&page);
    if !orphans.is_empty() {
        println!("\n{}", "Otros".style(theme::strong()));
        for template in orphans {
            println!(
                "  {}  {}",
                template.key.style(theme::accent()),
                template.display_name
            );
        }
    }

    Ok(())
}

/// A project, which is the one thing this tool could not make until now.
pub async fn create_project(
    client: &ApiClient,
    name: &str,
    description: Option<&str>,
    workspace_reference: Option<&str>,
) -> Result<()> {
    // Resolved here rather than passed through, so `--workspace equipo` works
    // the same way every other name in this tool does.
    let workspace = match workspace_reference {
        Some(reference) => Some(client.find_workspace(Some(reference)).await?),
        None => None,
    };

    let project = client
        .create_project(name, description, workspace.as_ref().map(|w| w.id.as_str()))
        .await?;

    println!(
        "  {} {} {}",
        theme::CHECK.style(theme::success()),
        project.name.style(theme::strong()),
        format!("({})", project.slug).style(theme::muted()),
    );
    println!(
        "  {}",
        format!("fundaia new {} <nombre> --repo <owner/repo>", project.slug).style(theme::muted()),
    );

    Ok(())
}

/// A persistent directory. Nothing is deployed: the volume is in the container
/// from the next deployment on, and saying so is better than restarting a
/// service somebody was only configuring.
pub async fn attach_volume(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    mount_path: &str,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;
    let volume = client.attach_volume(&service.id, mount_path).await?;

    println!(
        "  {} {} en {}",
        theme::CHECK.style(theme::success()),
        volume.mount_path.style(theme::strong()),
        service.name.style(theme::strong()),
    );
    println!(
        "  {}",
        "Estará dentro del contenedor a partir del próximo despliegue.".style(theme::muted()),
    );

    Ok(())
}

/// Changes how much disk a volume may hold.
///
/// The size is asked for in gigabytes because that is the unit the plans are
/// written in and the only one the server accepts — a flag taking megabytes
/// would let somebody type 5000 and be refused for not being a multiple of 1024,
/// which is a rule nobody should have to know.
///
/// **Nothing is deployed and nothing restarts.** The size is a reservation the
/// plan is measured against and the meter prices, not a mount option, so the
/// container underneath never learns it changed.
pub async fn resize_volume(client: &ApiClient, volume_id: &str, gigabytes: u64) -> Result<()> {
    let volume = client.resize_volume(volume_id, gigabytes * 1024).await?;

    println!(
        "  {} {} pasa a {} GB",
        theme::CHECK.style(theme::success()),
        volume.mount_path.style(theme::strong()),
        gigabytes.style(theme::strong()),
    );
    println!(
        "  {}",
        "El contenedor sigue como estaba: esto es lo que el plan reserva, no un montaje."
            .style(theme::muted()),
    );

    Ok(())
}

/// Replaces the Containerfile, after which it is never regenerated.
///
/// The file comes from a path or from stdin, because the shape of this is
/// `fundaia recipe show … --plain > Containerfile`, edit it, hand it back.
pub async fn edit_recipe(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    file: &str,
) -> Result<()> {
    let containerfile = read_text(file)?;

    if containerfile.trim().is_empty() {
        bail!("el Containerfile está vacío");
    }

    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;
    client.edit_recipe(&service.id, &containerfile).await?;

    println!(
        "  {} Containerfile de {}",
        theme::CHECK.style(theme::success()),
        service.name.style(theme::strong()),
    );
    println!(
        "  {}",
        "A partir de ahora se despliega este, no el generado.".style(theme::muted()),
    );

    Ok(())
}

/// A whole `.env` in one request.
pub async fn import_variables(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    file: &str,
    secret: bool,
) -> Result<()> {
    let variables = dotenv::variables_in(&read_text(file)?, secret);

    if variables.is_empty() {
        bail!("no hay ninguna variable en {file}");
    }

    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;
    let imported = client.import_variables(&service.id, &variables).await?;

    println!(
        "  {} {} en {}{}",
        theme::CHECK.style(theme::success()),
        format!("{imported} variables").style(theme::strong()),
        service.name.style(theme::strong()),
        if secret { " (secretas)" } else { "" },
    );

    for variable in variables.iter().take(5) {
        println!("  {}", variable.key.style(theme::muted()));
    }
    if variables.len() > 5 {
        println!(
            "  {}",
            format!("y {} más", variables.len() - 5).style(theme::muted())
        );
    }

    Ok(())
}

/// A path, or `-` for standard input.
fn read_text(file: &str) -> Result<String> {
    if file == "-" {
        let mut text = String::new();
        std::io::Read::read_to_string(&mut std::io::stdin(), &mut text)
            .context("no se ha podido leer la entrada estándar")?;
        return Ok(text);
    }

    std::fs::read_to_string(file).with_context(|| format!("no se ha podido leer {file}"))
}

pub async fn take_backup(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    println!(
        "  {} copiando el volumen de {}…",
        theme::ARROW.style(theme::muted()),
        service.name.style(theme::strong()),
    );

    let backup = client.take_backup(&service.id).await?;

    if backup.status == "failed" {
        bail!(
            "la copia falló: {}",
            backup
                .failure_message
                .unwrap_or_else(|| "sin motivo".to_owned())
        );
    }

    println!(
        "  {} copia {} hecha",
        theme::CHECK.style(theme::success()),
        backup.id.style(theme::strong()),
    );
    // The copy is real either way; what this says is whether it is also
    // somewhere the disk it sits on cannot take with it.
    if let Some(reason) = &backup.replication_error {
        println!(
            "  {} está en el servidor, pero no se pudo subir al remoto: {}",
            theme::CROSS.style(theme::warning()),
            reason
        );
    } else if backup.replicated_at.is_some() {
        println!(
            "  {}",
            "También está fuera de la máquina.".style(theme::muted())
        );
    }

    Ok(())
}

/// Turns schedules on. With none, the service stops being copied automatically.
pub async fn schedule_backups(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    schedules: &[String],
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let applied = client.schedule_backups(&service.id, schedules).await?;

    if applied.is_empty() {
        println!(
            "  {} {} ya no se copia solo",
            theme::CHECK.style(theme::success()),
            service.name.style(theme::strong()),
        );
        println!(
            "  {}",
            "Las copias que ya existen se quedan donde están.".style(theme::muted())
        );
        return Ok(());
    }

    println!(
        "  {} {} se copiará: {}",
        theme::CHECK.style(theme::success()),
        service.name.style(theme::strong()),
        applied.join(", ").style(theme::strong()),
    );

    Ok(())
}

/// Puts a copy back, which overwrites the volume.
///
/// The service name has to be typed back, like deleting one. This is the only
/// command here that destroys data somebody did not ask to lose, and the server
/// taking a safety copy first is a floor rather than a licence to be casual.
pub async fn restore_backup(
    client: &ApiClient,
    backup_id: &str,
    confirmation: Option<&str>,
) -> Result<()> {
    if confirmation != Some(backup_id) {
        bail!(
            "escribe `--confirm {backup_id}` para restaurarla: se sobrescribe el volumen entero y el servicio se reinicia"
        );
    }

    println!(
        "  {} copia de seguridad previa, parando el servicio y restaurando…",
        theme::ARROW.style(theme::muted()),
    );

    let backup = client.restore_backup(backup_id).await?;

    println!(
        "  {} volumen restaurado desde {}",
        theme::CHECK.style(theme::success()),
        backup.id.style(theme::strong()),
    );
    println!(
        "  {}",
        "Antes de sobrescribir se guardó una copia del estado anterior.".style(theme::muted()),
    );

    Ok(())
}

pub async fn lock_backup(client: &ApiClient, backup_id: &str, locked: bool) -> Result<()> {
    let backup = client.lock_backup(backup_id, locked).await?;

    println!(
        "  {} {} {}",
        theme::CHECK.style(theme::success()),
        backup.id.style(theme::strong()),
        if locked {
            "guardada — la retención ya no la borrará"
        } else {
            "vuelve a estar sujeta a la retención"
        },
    );

    Ok(())
}

pub async fn delete_backup(client: &ApiClient, backup_id: &str) -> Result<()> {
    client.delete_backup(backup_id).await?;
    println!(
        "  {} copia {} eliminada",
        theme::CHECK.style(theme::success()),
        backup_id.style(theme::strong()),
    );

    Ok(())
}

/// Replaces the configuration text. From then on the form leaves it alone.
pub async fn edit_service_config(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    file: &str,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let content = read_text(file)?;

    if content.trim().is_empty() {
        bail!("la configuración está vacía");
    }

    client.edit_service_config(&found.id, &content).await?;

    println!(
        "  {} configuración de {}",
        theme::CHECK.style(theme::success()),
        found.name.style(theme::strong()),
    );
    println!(
        "  {}",
        "editada a mano — el formulario ya no la sobrescribe".style(theme::muted()),
    );
    Ok(())
}

/// Records what somebody concluded about an incident.
///
/// `resolved` and `ignored` are different on purpose: a resolved incident that
/// happens again is reopened, which is how you find out the fix did not work,
/// and an ignored one stays ignored however often it recurs.
pub async fn decide_incident(
    client: &ApiClient,
    incident_id: &str,
    status: &str,
    format: Format,
) -> Result<()> {
    let incident = client.decide_incident(incident_id, status).await?;

    if format.is_json() {
        output::emit(&incident);
        return Ok(());
    }

    println!(
        "  {} incidencia {} · {}",
        theme::CHECK.style(theme::success()),
        incident.status,
        truncate(&incident.shape, 60)
    );
    Ok(())
}

/// Approves a commit somebody outside the workspace pushed, and deploys it.
///
/// Answers as soon as the deployment is queued, the same as `deploy --detach`:
/// what was being waited on is a person's decision, and that has already
/// happened by the time this runs.
pub async fn approve_deployment(
    client: &ApiClient,
    approval_id: &str,
    format: Format,
) -> Result<()> {
    let deployment = client.approve_deployment(approval_id).await?;

    if format.is_json() {
        output::emit(&deployment);
        return Ok(());
    }

    println!(
        "  {} aprobado · despliegue #{} · sigue con `fundaia logs`",
        theme::CHECK.style(theme::success()),
        deployment.number
    );
    Ok(())
}

/// Refuses a commit, for good.
///
/// The same commit reaching the branch again is not filed a second time, so
/// this is the answer for a push that should never deploy — not a way to defer
/// the decision.
pub async fn reject_deployment(
    client: &ApiClient,
    approval_id: &str,
    format: Format,
) -> Result<()> {
    let answer = client.reject_deployment(approval_id).await?;

    if format.is_json() {
        output::emit(&answer);
        return Ok(());
    }

    println!(
        "  {} rechazado · ese commit no se desplegará",
        theme::CHECK.style(theme::success())
    );
    Ok(())
}

/// Asks the platform to fix an incident.
///
/// Returns as soon as the run has started: the work is minutes long and holding
/// a terminal open for it would make every script that calls this hang.
pub async fn fix_incident(client: &ApiClient, incident_id: &str, format: Format) -> Result<()> {
    let run = client.fix_incident(incident_id).await?;

    if format.is_json() {
        output::emit(&run);
        return Ok(());
    }

    println!(
        "  {} arreglando · {} · sigue con `fundaia autofix`",
        theme::CHECK.style(theme::success()),
        run.id
    );
    Ok(())
}

/// Puts one service where it is told, by the coordinates `canvas` prints.
///
/// The service is named the way it is everywhere else — id, slug or the name on
/// screen — and the id sent is the *service* id rather than the service
/// environment one, which is what the canvas is keyed on.
pub async fn move_on_canvas(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    x: i64,
    y: i64,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;

    let view = client
        .place_on_canvas(
            &project.id,
            &[CanvasPlacement {
                service_id: service.service_id.clone(),
                x,
                y,
            }],
        )
        .await?;

    if format.is_json() {
        output::emit(&view);
        return Ok(());
    }

    // Read back from the answer rather than echoed: the server snaps to the
    // grid, so what was asked for and what happened differ by up to four units.
    let placed = view
        .nodes
        .iter()
        .find(|node| node.service_id == service.service_id);

    println!(
        "  {} {} {}",
        theme::CHECK.style(theme::success()),
        service.name.style(theme::strong()),
        match placed {
            Some(node) => format!("({}, {})", node.x, node.y)
                .style(theme::muted())
                .to_string(),
            None => String::new(),
        },
    );

    Ok(())
}

/// Lays a whole project out again, by one of the arrangements the server knows.
///
/// It overwrites every position in the project, which is said out loud because
/// there is nothing to undo it with: a canvas somebody spent an afternoon
/// arranging by hand is gone in one call.
pub async fn arrange_canvas(
    client: &ApiClient,
    project_reference: &str,
    layout: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let view = client.arrange_canvas(&project.id, layout).await?;

    if format.is_json() {
        output::emit(&view);
        return Ok(());
    }

    println!(
        "  {} {} {}",
        theme::CHECK.style(theme::success()),
        project.name.style(theme::strong()),
        format!("{} servicios, en {}", view.nodes.len(), layout).style(theme::muted()),
    );

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::models::TemplateCategory;
    use reqwest::StatusCode;

    fn template(key: &str, category: &str) -> Template {
        Template {
            key: key.to_owned(),
            display_name: key.to_owned(),
            image: String::new(),
            category: category.to_owned(),
            summary: String::new(),
            memory_mb: 512,
            setup: None,
        }
    }

    fn catalogue() -> TemplatesPage {
        TemplatesPage {
            templates: vec![
                template("postgres-16", "data"),
                template("traefik-3", "traffic"),
                template("something-new", "quantum"),
            ],
            categories: vec![TemplateCategory {
                id: "data".to_owned(),
                label: "Datos".to_owned(),
                summary: String::new(),
            }],
        }
    }

    #[test]
    fn it_should_group_a_component_under_its_own_category() {
        assert_eq!(entries_of(&catalogue(), "data").len(), 1);
    }

    #[test]
    fn it_should_leave_a_category_with_nothing_in_it_empty() {
        assert!(entries_of(&catalogue(), "agents").is_empty());
    }

    /// A CLI older than the server must not hide a component it cannot place.
    #[test]
    fn it_should_still_list_a_component_whose_category_it_does_not_know() {
        let page = catalogue();
        assert_eq!(ungrouped(&page).len(), 2);
    }

    fn refusal(code: &str) -> anyhow::Error {
        ApiError {
            status: StatusCode::NOT_FOUND,
            code: code.to_owned(),
            message: "template 'claude-code' does not exist".to_owned(),
        }
        .into()
    }

    #[test]
    fn it_should_say_who_may_add_a_component_the_server_refused() {
        let explained = explain_template_refusal(refusal("not_found"), "claude-code");
        assert!(explained
            .to_string()
            .contains("esta cuenta no puede añadirlo"));
    }

    #[test]
    fn it_should_name_the_component_it_could_not_add() {
        let explained = explain_template_refusal(refusal("not_found"), "claude-code");
        assert!(explained.to_string().contains("claude-code"));
    }

    #[test]
    fn it_should_keep_the_server_answer_as_the_cause() {
        let explained = explain_template_refusal(refusal("not_found"), "claude-code");
        assert!(explained.downcast_ref::<ApiError>().is_some());
    }

    #[test]
    fn it_should_leave_a_failure_that_is_not_a_missing_component_alone() {
        let explained = explain_template_refusal(refusal("conflict"), "claude-code");
        assert!(!explained.to_string().contains("dueño"));
    }

    fn option(id: &str) -> crate::api::models::ClaudeOption {
        crate::api::models::ClaudeOption {
            id: id.to_owned(),
            label: id.to_owned(),
            summary: String::new(),
        }
    }

    #[test]
    fn it_should_mark_the_default_among_the_ids() {
        let ids = ids_of(&[option("low"), option("high"), option("max")], "high");
        assert_eq!(ids, "low, high*, max");
    }

    #[test]
    fn it_should_never_print_a_token_only_whether_there_is_one() {
        assert!(!credential_word(true, false).contains("sk-ant"));
    }

    #[test]
    fn it_should_say_a_missing_token_will_fail_every_prompt() {
        assert!(credential_word(false, false).contains("fallará"));
    }

    #[test]
    fn it_should_send_nothing_about_claude_when_nothing_was_said() {
        let patch = AgentSetupPatch {
            model: None,
            effort: None,
            setup_token: None,
        };
        assert!(patch.is_empty());
    }
}