aer 0.2.1

A command-line toolkit for creatives.
Documentation
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
//! Kit resolution and pre-canonicalization.
//!
//! Kits are reusable asset packages fetched from git repositories
//! and made available to the processing pipeline under a namespace.

use std::collections::BTreeMap;
use std::future::Future;
use std::io;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use tokio::fs;
use tokio::process::Command;

use codas::types::cryptography::CryptoHasher;

use crate::proc::canonicalize::CanonicalizeProcessor;
use crate::proc::{MediaType, ProcessingError};
use crate::tool::KitConfig;

/// The directory within `.aer/` where cached (gitignored) kits live.
const CACHED_KITS_DIR: &str = ".aer/kits/cached";

/// The directory within `.aer/` where vendored (committed) kits live.
const VENDORED_KITS_DIR: &str = ".aer/kits/vendored";

/// Path to the kit lockfile relative to the config directory.
const LOCKFILE_PATH: &str = ".aer/kits/lockfile.toml";

/// Dummy root used during pre-canonicalization.
/// Replaced with `/` after processing.
const PRECANON_ROOT: &str = "http://KITPRECANON/";

/// Contents of `.aer/.gitignore`.
const GITIGNORE_CONTENT: &str = "# Auto-generated by aer. Do not edit.\nkits/cached/\ntools/\n";

/// Contents of `.aer/.gitattributes`.
const GITATTRIBUTES_CONTENT: &str = "\
# Auto-generated by aer. Do not edit.\n\
kits/vendored/** -diff\n\
kits/vendored/** merge=ours\n";

/// Lockfile tracking vendored kit state.
#[derive(Debug, Serialize, Deserialize, Default)]
struct Lockfile {
    #[serde(default)]
    kits: BTreeMap<String, LockfileEntry>,
}

/// A single entry in the lockfile.
#[derive(Debug, Serialize, Deserialize, Clone)]
struct LockfileEntry {
    git: String,
    #[serde(rename = "ref")]
    git_ref: String,
    commit: String,
    #[serde(default)]
    hash: String,
}

/// Reads the lockfile from disk, returning `None` if it doesn't exist.
async fn read_lockfile(config_dir: &Path) -> io::Result<Option<Lockfile>> {
    let path = config_dir.join(LOCKFILE_PATH);
    match fs::read_to_string(&path).await {
        Ok(content) => {
            let lockfile: Lockfile = toml::from_str(&content).map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("invalid lockfile: {}", e),
                )
            })?;
            Ok(Some(lockfile))
        }
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e),
    }
}

/// Writes the lockfile to disk.
async fn write_lockfile(config_dir: &Path, lockfile: &Lockfile) -> io::Result<()> {
    let path = config_dir.join(LOCKFILE_PATH);
    let content = toml::to_string_pretty(lockfile)
        .map_err(|e| io::Error::other(format!("failed to serialize lockfile: {}", e)))?;
    fs::write(&path, content).await
}

/// Ensures the `.aer/` directory structure exists with correct gitignore/gitattributes.
async fn ensure_aer_directory(config_dir: &Path) -> io::Result<()> {
    let aer_dir = config_dir.join(".aer");
    fs::create_dir_all(aer_dir.join("kits/cached")).await?;
    fs::create_dir_all(aer_dir.join("kits/vendored")).await?;

    write_if_changed(&aer_dir.join(".gitignore"), GITIGNORE_CONTENT).await?;
    write_if_changed(&aer_dir.join(".gitattributes"), GITATTRIBUTES_CONTENT).await?;

    Ok(())
}

/// Writes `content` to `path` only if the file is missing or differs.
async fn write_if_changed(path: &Path, content: &str) -> io::Result<()> {
    match fs::read_to_string(path).await {
        Ok(existing) if existing == content => Ok(()),
        _ => fs::write(path, content).await,
    }
}

/// Runs a command and returns its trimmed stdout. Wraps non-zero exits into `io::Error`.
async fn run_cmd(mut cmd: Command, error_context: &str) -> io::Result<String> {
    let output = cmd.output().await?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(io::Error::other(format!(
            "{}: {}",
            error_context,
            stderr.trim()
        )));
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Checks that vendored kits match the lockfile. Returns an error if any drift is detected.
///
/// Verifies both config-level drift (git URL / ref changed) and file-level integrity
/// (vendored files were modified since last refresh).
async fn check_lockfile_drift(
    kits: &BTreeMap<String, KitConfig>,
    lockfile: Option<&Lockfile>,
    config_dir: &Path,
) -> io::Result<()> {
    let vendored_dir = config_dir.join(VENDORED_KITS_DIR);

    for (name, kit) in kits {
        if let Some(lf) = lockfile {
            if let Some(entry) = lf.kits.get(name) {
                if entry.git != kit.git_url || entry.git_ref != kit.git_ref {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!(
                            "Kit `{}` has changed since last refresh (config: git={} ref={}, lockfile: git={} ref={}). \
                             Run `aer kits refresh` to update.",
                            name, kit.git_url, kit.git_ref, entry.git, entry.git_ref
                        ),
                    ));
                }
                // Verify file integrity for vendored kits.
                if kit.vendored && !entry.hash.is_empty() {
                    let vendored_kit_dir = vendored_dir.join(name);
                    if fs::try_exists(&vendored_kit_dir).await? {
                        let current_hash = hash_directory(&vendored_kit_dir).await?;
                        if current_hash != entry.hash {
                            return Err(io::Error::new(
                                io::ErrorKind::InvalidData,
                                format!(
                                    "Kit `{}` vendored files have been modified. \
                                     Run `aer kits refresh --update` to restore from git.",
                                    name
                                ),
                            ));
                        }
                    }
                }
            } else if kit.vendored {
                return Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!(
                        "Kit `{}` is vendored but missing from lockfile. Run `aer kits refresh` to update.",
                        name
                    ),
                ));
            }
        } else if kit.vendored {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!(
                    "Kit `{}` is vendored but no lockfile exists. Run `aer kits refresh` to update.",
                    name
                ),
            ));
        }
    }
    Ok(())
}

/// Computes a hash of all file contents in a directory (sorted by path).
fn hash_directory(
    dir: &Path,
) -> std::pin::Pin<Box<dyn Future<Output = io::Result<String>> + Send + '_>> {
    Box::pin(async move {
        let mut hasher = CryptoHasher::default();
        let mut paths = Vec::new();
        collect_file_paths(dir, dir, &mut paths).await?;
        paths.sort();
        for path in &paths {
            // Hash the relative path so renames are detected.
            hasher.write(path.as_bytes());
            let full = dir.join(path);
            let content = fs::read(&full).await?;
            hasher.write(&content);
        }
        Ok(hasher.finalize().to_hex().to_string())
    })
}

/// Recursively collects relative file paths in a directory.
fn collect_file_paths<'a>(
    base: &'a Path,
    dir: &'a Path,
    out: &'a mut Vec<String>,
) -> std::pin::Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>> {
    Box::pin(async move {
        let mut entries = fs::read_dir(dir).await?;
        while let Some(entry) = entries.next_entry().await? {
            let file_type = entry.file_type().await?;
            let path = entry.path();
            if file_type.is_dir() {
                collect_file_paths(base, &path, out).await?;
            } else if let Ok(rel) = path.strip_prefix(base) {
                out.push(rel.to_string_lossy().to_string());
            }
        }
        Ok(())
    })
}

/// Resolves a remote ref to its commit hash without cloning.
async fn git_ls_remote(url: &str, git_ref: &str) -> io::Result<Option<String>> {
    let mut cmd = Command::new("git");
    cmd.args(["ls-remote", url, git_ref]);
    let output = run_cmd(cmd, "git ls-remote failed").await?;
    // Output format: "<hash>\t<ref>\n" — take the first hash.
    Ok(output.split_whitespace().next().map(|s| s.to_string()))
}

/// Fetches a git repository at the given ref using init + fetch + checkout.
async fn git_fetch(url: &str, git_ref: &str, dest: &Path) -> io::Result<()> {
    let mut cmd = Command::new("git");
    cmd.arg("init").arg(dest);
    run_cmd(cmd, "git init failed").await?;

    let mut cmd = Command::new("git");
    cmd.arg("-C")
        .arg(dest)
        .args(["fetch", "--depth", "1", url, git_ref]);
    run_cmd(cmd, "git fetch failed").await?;

    let mut cmd = Command::new("git");
    cmd.arg("-C").arg(dest).args(["checkout", "FETCH_HEAD"]);
    run_cmd(cmd, "git checkout failed").await?;

    Ok(())
}

/// Returns the HEAD commit hash of a git repository.
async fn git_commit_hash(repo: &Path) -> io::Result<String> {
    let mut cmd = Command::new("git");
    cmd.arg("-C").arg(repo).args(["rev-parse", "HEAD"]);
    run_cmd(cmd, "git rev-parse failed").await
}

/// Returns the current ref of a git repository by inspecting its state.
/// Tries branch name, then tag name, then commit hash.
async fn git_current_ref(repo: &Path) -> io::Result<Option<String>> {
    let mut cmd = Command::new("git");
    cmd.arg("-C")
        .arg(repo)
        .args(["symbolic-ref", "--short", "HEAD"]);
    if let Ok(branch) = run_cmd(cmd, "git symbolic-ref").await {
        return Ok(Some(branch));
    }

    let mut cmd = Command::new("git");
    cmd.arg("-C")
        .arg(repo)
        .args(["describe", "--tags", "--exact-match", "HEAD"]);
    if let Ok(tag) = run_cmd(cmd, "git describe").await {
        return Ok(Some(tag));
    }

    let mut cmd = Command::new("git");
    cmd.arg("-C").arg(repo).args(["rev-parse", "HEAD"]);
    if let Ok(hash) = run_cmd(cmd, "git rev-parse").await {
        return Ok(Some(hash));
    }

    Ok(None)
}

/// Returns true if the path is a symlink.
async fn is_symlink(path: &Path) -> bool {
    fs::symlink_metadata(path)
        .await
        .map(|m| m.is_symlink())
        .unwrap_or(false)
}

/// A resolved kit ready for use in the build pipeline.
#[derive(Debug, Clone)]
pub struct ResolvedKit {
    pub name: String,
    pub local_path: PathBuf,
    pub dest: String,
}

/// Resolves all declared kits, returning their local paths.
///
/// Resolution order per kit:
/// 1. `path` set and exists → use local path (has `kit/` subdir)
/// 2. `vendored == true` and vendored dir exists → use vendored (contents of `kit/` directly)
/// 3. Cached dir exists and ref matches → use cached (has `kit/` subdir)
/// 4. Clone into cached dir
///
/// After resolution, checks lockfile drift for all vendored kits.
pub async fn resolve_kits(
    kits: &BTreeMap<String, KitConfig>,
    config_dir: &Path,
) -> io::Result<Vec<ResolvedKit>> {
    if kits.is_empty() {
        return Ok(Vec::new());
    }

    ensure_aer_directory(config_dir).await?;

    let cached_dir = config_dir.join(CACHED_KITS_DIR);
    let vendored_dir = config_dir.join(VENDORED_KITS_DIR);

    // Read lockfile and check drift before resolving.
    let lockfile = read_lockfile(config_dir).await?;
    check_lockfile_drift(kits, lockfile.as_ref(), config_dir).await?;

    let mut resolved = Vec::with_capacity(kits.len());

    for (name, kit) in kits {
        let dest = kit
            .dest
            .clone()
            .unwrap_or_else(|| format!("/vendor/kits/{}", name));

        // 1. Local path override.
        if let Some(local_path) = &kit.path {
            let local = config_dir.join(local_path);
            if fs::try_exists(&local).await? {
                let kit_assets_dir = local.join("kit");
                if !fs::try_exists(&kit_assets_dir).await? {
                    return Err(io::Error::new(
                        io::ErrorKind::NotFound,
                        format!("Kit `{}` has no `kit/` directory", name),
                    ));
                }
                tracing::info!("Kit `{}`: using local path {}", name, local.display());
                resolved.push(ResolvedKit {
                    name: name.clone(),
                    local_path: kit_assets_dir,
                    dest,
                });
                continue;
            }
            tracing::debug!(
                "Kit `{}`: local path {} not found, falling back",
                name,
                local.display()
            );
        }

        // 2. Vendored kit.
        if kit.vendored {
            let vendored_kit_dir = vendored_dir.join(name);
            if fs::try_exists(&vendored_kit_dir).await? {
                tracing::info!("Kit `{}`: using vendored copy", name);
                resolved.push(ResolvedKit {
                    name: name.clone(),
                    local_path: vendored_kit_dir,
                    dest,
                });
                continue;
            }
            // Vendored but directory missing — drift check above should have caught this,
            // but be explicit.
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!(
                    "Kit `{}` is vendored but not found at {}. Run `aer kits refresh` to populate.",
                    name,
                    vendored_kit_dir.display()
                ),
            ));
        }

        // 3. Check cache: compare git state against configured ref.
        let kit_dir = cached_dir.join(name);
        if fs::try_exists(&kit_dir).await? && !is_symlink(&kit_dir).await {
            if let Some(current) = git_current_ref(&kit_dir).await?
                && (current == kit.git_ref
                    || current.starts_with(&kit.git_ref)
                    || kit.git_ref.starts_with(&current))
            {
                tracing::info!("Kit `{}`: cached at ref {}", name, kit.git_ref);
                let kit_assets_dir = kit_dir.join("kit");
                if !fs::try_exists(&kit_assets_dir).await? {
                    return Err(io::Error::new(
                        io::ErrorKind::NotFound,
                        format!("Kit `{}` has no `kit/` directory", name),
                    ));
                }
                resolved.push(ResolvedKit {
                    name: name.clone(),
                    local_path: kit_assets_dir,
                    dest,
                });
                continue;
            }
            // Ref changed or unreadable — remove stale clone.
            tracing::info!("Kit `{}`: ref changed, re-cloning", name);
            fs::remove_dir_all(&kit_dir).await?;
        } else if is_symlink(&kit_dir).await {
            // Symlink from a previous local override — remove it.
            fs::remove_file(&kit_dir).await?;
        }

        // 4. Fresh clone into cache.
        git_fetch(&kit.git_url, &kit.git_ref, &kit_dir).await?;
        tracing::info!("Kit `{}`: resolved at ref {}", name, kit.git_ref);

        let kit_assets_dir = kit_dir.join("kit");
        if !fs::try_exists(&kit_assets_dir).await? {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("Kit `{}` has no `kit/` directory", name),
            ));
        }

        resolved.push(ResolvedKit {
            name: name.clone(),
            local_path: kit_assets_dir,
            dest,
        });
    }

    Ok(resolved)
}

/// Refreshes vendored kits by fetching from their git sources.
///
/// Fetches each vendored kit, copies the contents of `kit/` into the vendored
/// directory, and updates the lockfile.
pub async fn refresh_kits(
    kits: &BTreeMap<String, KitConfig>,
    config_dir: &Path,
    target_kit: Option<&str>,
    force_update: bool,
) -> io::Result<()> {
    ensure_aer_directory(config_dir).await?;

    let mut lockfile = read_lockfile(config_dir).await?.unwrap_or_default();
    let vendored_dir = config_dir.join(VENDORED_KITS_DIR);

    let mut any_refreshed = false;

    for (name, kit) in kits {
        if !kit.vendored {
            continue;
        }
        if let Some(target) = target_kit
            && name != target
        {
            continue;
        }

        // Check if lockfile already matches and skip unless forced.
        if !force_update
            && let Some(entry) = lockfile.kits.get(name)
            && entry.git == kit.git_url
            && entry.git_ref == kit.git_ref
        {
            let vendored_kit_dir = vendored_dir.join(name);
            if fs::try_exists(&vendored_kit_dir).await? {
                // The ref string matches, but for mutable refs (branches) the
                // upstream commit may have changed. Resolve the remote ref and
                // compare against the locked commit hash.
                let remote_commit = git_ls_remote(&kit.git_url, &kit.git_ref).await?;
                if remote_commit.as_deref() == Some(entry.commit.as_str()) {
                    tracing::info!("Kit `{}`: already up to date", name);
                    continue;
                }
                tracing::info!(
                    "Kit `{}`: remote ref updated ({} -> {})",
                    name,
                    &entry.commit[..12.min(entry.commit.len())],
                    remote_commit
                        .as_deref()
                        .map(|c| &c[..12.min(c.len())])
                        .unwrap_or("unknown"),
                );
            }
        }

        tracing::info!("Kit `{}`: fetching from {}", name, kit.git_url);

        // Fetch into a temp directory.
        let temp_dir = config_dir.join(format!(".aer/kits/.tmp-{}", name));
        if fs::try_exists(&temp_dir).await? {
            fs::remove_dir_all(&temp_dir).await?;
        }
        fs::create_dir_all(&temp_dir).await?;

        let fetch_result = git_fetch(&kit.git_url, &kit.git_ref, &temp_dir).await;
        if let Err(e) = fetch_result {
            let _ = fs::remove_dir_all(&temp_dir).await;
            return Err(e);
        }

        // Get commit hash.
        let commit = git_commit_hash(&temp_dir).await?;

        // Validate kit/ subdir exists.
        let temp_kit_dir = temp_dir.join("kit");
        if !fs::try_exists(&temp_kit_dir).await? {
            let _ = fs::remove_dir_all(&temp_dir).await;
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("Kit `{}` has no `kit/` directory in its repository", name),
            ));
        }

        // Replace vendored copy (rename is atomic on the same filesystem).
        let vendored_kit_dir = vendored_dir.join(name);
        if fs::try_exists(&vendored_kit_dir).await? {
            fs::remove_dir_all(&vendored_kit_dir).await?;
        }
        fs::rename(&temp_kit_dir, &vendored_kit_dir).await?;

        // Clean up remaining temp files (.git, etc.).
        let _ = fs::remove_dir_all(&temp_dir).await;

        // Compute integrity hash of vendored contents.
        let hash = hash_directory(&vendored_kit_dir).await?;

        // Update lockfile entry.
        lockfile.kits.insert(
            name.clone(),
            LockfileEntry {
                git: kit.git_url.clone(),
                git_ref: kit.git_ref.clone(),
                commit,
                hash,
            },
        );

        tracing::info!("Kit `{}`: vendored at ref {}", name, kit.git_ref);
        any_refreshed = true;
    }

    if let Some(target) = target_kit {
        if !kits.contains_key(target) {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("Kit `{}` not found in configuration", target),
            ));
        }
        if !kits[target].vendored {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("Kit `{}` is not configured as vendored", target),
            ));
        }
    }

    write_lockfile(config_dir, &lockfile).await?;

    if any_refreshed {
        tracing::info!("Lockfile updated");
    }

    Ok(())
}

/// Pre-canonicalizes kit assets by rewriting relative URLs
/// to absolute paths under the kit's `dest`.
///
/// Returns a list of `(relative_output_path, content_bytes)` pairs.
pub fn pre_canonicalize_kit_assets(
    assets: &[(String, Vec<u8>)],
    dest: &str,
) -> Vec<(String, Vec<u8>)> {
    let processor = match CanonicalizeProcessor::new(PRECANON_ROOT) {
        Some(p) => p,
        None => return assets.to_vec(),
    };

    let dest_trimmed = dest.trim_start_matches('/');

    assets
        .iter()
        .map(|(relative_path, content)| {
            let prefixed_path = if dest_trimmed.is_empty() {
                relative_path.clone()
            } else {
                format!("{}/{}", dest_trimmed, relative_path)
            };

            let media_type = relative_path
                .rsplit('.')
                .next()
                .map(MediaType::from_extension)
                .unwrap_or(MediaType::Unknown {
                    extension: [String::new().into()],
                });

            let new_content = match media_type {
                MediaType::Css | MediaType::Scss => {
                    if let Ok(text) = std::str::from_utf8(content) {
                        let processed = processor.process_css(text, &prefixed_path);
                        let result = processed.replace(PRECANON_ROOT, "/");
                        result.into_bytes()
                    } else {
                        content.clone()
                    }
                }
                MediaType::Html => {
                    if let Ok(text) = std::str::from_utf8(content) {
                        match processor.process_html(text, &prefixed_path.into()) {
                            Ok(processed) => {
                                let result = processed.replace(PRECANON_ROOT, "/");
                                result.into_bytes()
                            }
                            Err(ProcessingError::Malformed { message }) => {
                                tracing::warn!(
                                    "Pre-canonicalization failed for {}: {}",
                                    relative_path,
                                    message
                                );
                                content.clone()
                            }
                            Err(_) => content.clone(),
                        }
                    } else {
                        content.clone()
                    }
                }
                _ => content.clone(),
            };

            (relative_path.clone(), new_content)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pre_canonicalizes_css_urls() {
        let css = r#"@font-face { src: url("../fonts/font.ttf"); }"#;
        let assets = vec![("styles/main.css".to_string(), css.as_bytes().to_vec())];

        let result = pre_canonicalize_kit_assets(&assets, "/vendor/kits/base");
        assert_eq!(result.len(), 1);

        let output = std::str::from_utf8(&result[0].1).unwrap();
        assert!(
            output.contains("/vendor/kits/base/fonts/font.ttf"),
            "Expected canonicalized URL, got: {}",
            output
        );
    }

    #[test]
    fn pre_canonicalizes_css_with_root_dest() {
        let css = r#"body { background: url("images/bg.png"); }"#;
        let assets = vec![("styles/main.css".to_string(), css.as_bytes().to_vec())];

        let result = pre_canonicalize_kit_assets(&assets, "/");
        let output = std::str::from_utf8(&result[0].1).unwrap();
        assert!(
            output.contains("/styles/images/bg.png"),
            "Expected canonicalized URL, got: {}",
            output
        );
    }

    #[test]
    fn pre_canonicalizes_html_hrefs() {
        let html = r#"<a href="../page.html">Link</a>"#;
        let assets = vec![("pages/index.html".to_string(), html.as_bytes().to_vec())];

        let result = pre_canonicalize_kit_assets(&assets, "/vendor/kits/base");
        let output = std::str::from_utf8(&result[0].1).unwrap();
        assert!(
            output.contains("/vendor/kits/base/page.html"),
            "Expected canonicalized URL, got: {}",
            output
        );
    }

    #[test]
    fn preserves_binary_assets() {
        let binary = vec![0u8, 1, 2, 3, 255];
        let assets = vec![("image.png".to_string(), binary.clone())];

        let result = pre_canonicalize_kit_assets(&assets, "/vendor/kits/base");
        assert_eq!(result[0].1, binary);
    }

    #[test]
    fn preserves_absolute_urls_in_css() {
        let css = r#"@font-face { src: url("/absolute/font.ttf"); }"#;
        let assets = vec![("styles/main.css".to_string(), css.as_bytes().to_vec())];

        let result = pre_canonicalize_kit_assets(&assets, "/vendor/kits/base");
        let output = std::str::from_utf8(&result[0].1).unwrap();
        // Absolute URLs get canonicalized against the PRECANON root,
        // then the root is stripped to /, leaving the original path.
        assert!(
            output.contains("/absolute/font.ttf"),
            "Expected preserved absolute URL, got: {}",
            output
        );
    }

    #[test]
    fn lockfile_round_trip() {
        let mut lockfile = Lockfile::default();
        lockfile.kits.insert(
            "brand".to_string(),
            LockfileEntry {
                git: "git@github.com:example/brand.git".to_string(),
                git_ref: "main".to_string(),
                commit: "abc123def456".to_string(),
                hash: "deadbeef".to_string(),
            },
        );

        let serialized = toml::to_string_pretty(&lockfile).unwrap();
        let deserialized: Lockfile = toml::from_str(&serialized).unwrap();

        assert_eq!(deserialized.kits.len(), 1);
        let entry = &deserialized.kits["brand"];
        assert_eq!(entry.git, "git@github.com:example/brand.git");
        assert_eq!(entry.git_ref, "main");
        assert_eq!(entry.commit, "abc123def456");
        assert_eq!(entry.hash, "deadbeef");
    }

    fn kit_config(git_ref: &str, vendored: bool) -> KitConfig {
        KitConfig {
            git_url: "git@github.com:example/brand.git".to_string(),
            git_ref: git_ref.to_string(),
            dest: None,
            path: None,
            vendored,
        }
    }

    fn lockfile_entry(git_ref: &str, hash: &str) -> LockfileEntry {
        LockfileEntry {
            git: "git@github.com:example/brand.git".to_string(),
            git_ref: git_ref.to_string(),
            commit: "abc123".to_string(),
            hash: hash.to_string(),
        }
    }

    #[tokio::test]
    async fn drift_detection_catches_ref_change() {
        let temp = tempfile::tempdir().unwrap();

        let mut kits = BTreeMap::new();
        kits.insert("brand".to_string(), kit_config("v2.0", true));

        let mut lockfile = Lockfile::default();
        lockfile
            .kits
            .insert("brand".to_string(), lockfile_entry("v1.0", "deadbeef"));

        let result = check_lockfile_drift(&kits, Some(&lockfile), temp.path()).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("has changed since last refresh"),
            "got: {}",
            err
        );
    }

    #[tokio::test]
    async fn drift_detection_catches_missing_vendored() {
        let temp = tempfile::tempdir().unwrap();

        let mut kits = BTreeMap::new();
        kits.insert("brand".to_string(), kit_config("main", true));

        let lockfile = Lockfile::default();
        let result = check_lockfile_drift(&kits, Some(&lockfile), temp.path()).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("missing from lockfile"), "got: {}", err);
    }

    #[tokio::test]
    async fn drift_detection_ok_for_matching_lockfile() {
        let temp = tempfile::tempdir().unwrap();

        // Create vendored dir with a file so the hash can be computed.
        let vendored_dir = temp.path().join(VENDORED_KITS_DIR).join("brand");
        fs::create_dir_all(&vendored_dir).await.unwrap();
        fs::write(vendored_dir.join("test.txt"), "hello")
            .await
            .unwrap();
        let expected_hash = hash_directory(&vendored_dir).await.unwrap();

        let mut kits = BTreeMap::new();
        kits.insert("brand".to_string(), kit_config("main", true));

        let mut lockfile = Lockfile::default();
        lockfile
            .kits
            .insert("brand".to_string(), lockfile_entry("main", &expected_hash));

        let result = check_lockfile_drift(&kits, Some(&lockfile), temp.path()).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn drift_detection_catches_file_modification() {
        let temp = tempfile::tempdir().unwrap();

        // Create vendored dir with a file.
        let vendored_dir = temp.path().join(VENDORED_KITS_DIR).join("brand");
        fs::create_dir_all(&vendored_dir).await.unwrap();
        fs::write(vendored_dir.join("test.txt"), "hello")
            .await
            .unwrap();
        let original_hash = hash_directory(&vendored_dir).await.unwrap();

        // Tamper with the file.
        fs::write(vendored_dir.join("test.txt"), "modified")
            .await
            .unwrap();

        let mut kits = BTreeMap::new();
        kits.insert("brand".to_string(), kit_config("main", true));

        let mut lockfile = Lockfile::default();
        lockfile
            .kits
            .insert("brand".to_string(), lockfile_entry("main", &original_hash));

        let result = check_lockfile_drift(&kits, Some(&lockfile), temp.path()).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("vendored files have been modified"),
            "got: {}",
            err
        );
    }

    #[tokio::test]
    async fn drift_detection_ok_for_non_vendored_without_lockfile() {
        let temp = tempfile::tempdir().unwrap();

        let mut kits = BTreeMap::new();
        kits.insert("brand".to_string(), kit_config("main", false));

        let result = check_lockfile_drift(&kits, None, temp.path()).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn ensure_aer_directory_is_idempotent() {
        let temp = tempfile::tempdir().unwrap();

        // First call creates everything.
        ensure_aer_directory(temp.path()).await.unwrap();
        assert!(
            fs::try_exists(temp.path().join(".aer/kits/cached"))
                .await
                .unwrap()
        );
        assert!(
            fs::try_exists(temp.path().join(".aer/kits/vendored"))
                .await
                .unwrap()
        );

        let gitignore = fs::read_to_string(temp.path().join(".aer/.gitignore"))
            .await
            .unwrap();
        assert_eq!(gitignore, GITIGNORE_CONTENT);

        let gitattributes = fs::read_to_string(temp.path().join(".aer/.gitattributes"))
            .await
            .unwrap();
        assert_eq!(gitattributes, GITATTRIBUTES_CONTENT);

        // Second call succeeds without error.
        ensure_aer_directory(temp.path()).await.unwrap();
    }
}