Skip to main content

devimg_core/
ai.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::path::{Path, PathBuf};
3
4use serde::{Deserialize, Serialize};
5
6use crate::config::{project_relative, resolve_project_path_checked, Config};
7use crate::manifest::{read_manifest, Manifest};
8use crate::pipeline::path_to_string;
9use crate::quality::manifest_quality_warnings;
10use crate::{scan_sources, Result};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
13#[serde(rename_all = "kebab-case")]
14pub enum AiProvider {
15    Openai,
16    Anthropic,
17}
18
19impl AiProvider {
20    pub fn label(self) -> &'static str {
21        match self {
22            Self::Openai => "openai",
23            Self::Anthropic => "anthropic",
24        }
25    }
26
27    pub fn credential_env_var(self) -> &'static str {
28        match self {
29            Self::Openai => "OPENAI_API_KEY",
30            Self::Anthropic => "ANTHROPIC_API_KEY",
31        }
32    }
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct AiConsentOptions {
37    pub provider: AiProvider,
38    pub model: String,
39    pub command: String,
40    pub config_path: PathBuf,
41    pub dry_run: bool,
42    pub include_images: bool,
43    pub output_path: Option<PathBuf>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
47pub struct AiConsentPreview {
48    pub provider: AiProvider,
49    pub model: String,
50    pub command: String,
51    pub config_path: String,
52    pub project_root: String,
53    pub mode: String,
54    pub dry_run: bool,
55    pub paths_included: bool,
56    pub image_bytes_included: bool,
57    pub output_path: Option<String>,
58    pub manifest_path: String,
59    pub report_path: String,
60    pub manifest_readable: bool,
61    pub source_files: Vec<AiSelectedFile>,
62    pub generated_outputs: Vec<AiGeneratedOutput>,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
66pub struct AiSelectedFile {
67    pub source_name: String,
68    pub path: String,
69    pub role: String,
70    pub width: u32,
71    pub height: u32,
72    pub format: String,
73    pub bytes: u64,
74    pub hash: String,
75    pub image_bytes_included: bool,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
79pub struct AiGeneratedOutput {
80    pub source_path: String,
81    pub output_path: String,
82    pub preset: String,
83    pub fit: String,
84    pub width: u32,
85    pub height: u32,
86    pub format: String,
87    pub bytes: u64,
88    pub hash: String,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
92pub struct AiProviderResponse {
93    pub provider: AiProvider,
94    pub model: String,
95    pub request_kind: String,
96    pub network_called: bool,
97    pub selected_file_count: usize,
98    pub generated_output_count: usize,
99}
100
101pub trait AiProviderClient {
102    fn consent_response(&self, preview: &AiConsentPreview) -> AiProviderResponse;
103}
104
105pub trait AiReviewProviderClient {
106    fn review(&self, request: &AiReviewRequest) -> Result<AiReviewProviderPayload>;
107}
108
109pub trait AiAltProviderClient {
110    fn alt(&self, request: &AiAltRequest) -> Result<AiAltProviderPayload>;
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub struct MockAiProviderClient {
115    provider: AiProvider,
116}
117
118impl MockAiProviderClient {
119    pub fn new(provider: AiProvider) -> Self {
120        Self { provider }
121    }
122}
123
124impl AiProviderClient for MockAiProviderClient {
125    fn consent_response(&self, preview: &AiConsentPreview) -> AiProviderResponse {
126        AiProviderResponse {
127            provider: self.provider,
128            model: preview.model.clone(),
129            request_kind: "consent-preview".to_string(),
130            network_called: false,
131            selected_file_count: preview.source_files.len(),
132            generated_output_count: preview.generated_outputs.len(),
133        }
134    }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct AiReviewOptions {
139    pub provider: AiProvider,
140    pub model: String,
141    pub command: String,
142    pub manifest_path: PathBuf,
143    pub project_root: PathBuf,
144    pub dry_run: bool,
145    pub include_images: bool,
146    pub image_detail: String,
147    pub max_images: usize,
148    pub ai_output_path: Option<PathBuf>,
149    pub markdown_path: Option<PathBuf>,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
153pub struct AiReviewRequest {
154    pub schema_version: u32,
155    pub provider: AiProvider,
156    pub model: String,
157    pub command: String,
158    pub manifest_path: String,
159    pub project_root: String,
160    pub mode: String,
161    pub dry_run: bool,
162    pub paths_included: bool,
163    pub image_bytes_included: bool,
164    pub image_detail: String,
165    pub max_images: usize,
166    pub ai_output_path: Option<String>,
167    pub markdown_path: Option<String>,
168    pub manifest_summary: AiReviewManifestSummary,
169    pub review_signals: Vec<String>,
170    pub outputs: Vec<AiReviewOutput>,
171    pub selected_images: Vec<AiReviewImageInput>,
172    pub skipped_image_count: usize,
173}
174
175#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
176pub struct AiReviewManifestSummary {
177    pub config_path: String,
178    pub config_hash: String,
179    pub source_count: usize,
180    pub output_count: usize,
181    pub source_bytes: u64,
182    pub output_bytes: u64,
183}
184
185#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
186pub struct AiReviewOutput {
187    pub source_path: String,
188    pub output_path: String,
189    pub preset: String,
190    pub fit: String,
191    pub width: u32,
192    pub height: u32,
193    pub format: String,
194    pub bytes: u64,
195    pub hash: String,
196    pub source_width: u32,
197    pub source_height: u32,
198    pub source_bytes: u64,
199    pub image_bytes_included: bool,
200    pub image_detail: Option<String>,
201}
202
203#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
204pub struct AiReviewImageInput {
205    pub output_path: String,
206    pub mime_type: String,
207    pub width: u32,
208    pub height: u32,
209    pub bytes: u64,
210    pub hash: String,
211    pub detail: String,
212}
213
214#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
215pub struct AiReviewProviderPayload {
216    #[serde(default)]
217    pub summary: String,
218    #[serde(default)]
219    pub observations: Vec<AiReviewObservation>,
220}
221
222#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
223pub struct AiReviewObservation {
224    pub category: String,
225    pub severity: String,
226    pub source_path: String,
227    pub preset: String,
228    pub output_path: String,
229    pub rationale: String,
230    pub suggested_next_command: String,
231}
232
233#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
234pub struct AiReviewReport {
235    pub schema_version: u32,
236    pub provider: AiProvider,
237    pub model: String,
238    pub command: String,
239    pub manifest_path: String,
240    pub project_root: String,
241    pub mode: String,
242    pub dry_run: bool,
243    pub paths_included: bool,
244    pub image_bytes_included: bool,
245    pub image_detail: String,
246    pub max_images: usize,
247    pub ai_output_path: Option<String>,
248    pub markdown_path: Option<String>,
249    pub provider_called: bool,
250    pub summary: AiReviewSummary,
251    pub review_signals: Vec<String>,
252    pub outputs: Vec<AiReviewOutput>,
253    pub selected_images: Vec<AiReviewImageInput>,
254    pub provider_summary: String,
255    pub observations: Vec<AiReviewObservation>,
256}
257
258#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
259pub struct AiReviewSummary {
260    pub source_count: usize,
261    pub output_count: usize,
262    pub selected_image_count: usize,
263    pub skipped_image_count: usize,
264    pub review_signal_count: usize,
265    pub observation_count: usize,
266}
267
268#[derive(Debug, Clone, PartialEq, Eq)]
269pub struct AiAltOptions {
270    pub provider: AiProvider,
271    pub model: String,
272    pub command: String,
273    pub config_path: PathBuf,
274    pub manifest_path: PathBuf,
275    pub project_root: PathBuf,
276    pub dry_run: bool,
277    pub include_images: bool,
278    pub image_detail: String,
279    pub max_images: usize,
280    pub output_path: Option<PathBuf>,
281    pub markdown_path: Option<PathBuf>,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
285pub struct AiAltRequest {
286    pub schema_version: u32,
287    pub provider: AiProvider,
288    pub model: String,
289    pub command: String,
290    pub config_path: String,
291    pub manifest_path: String,
292    pub project_root: String,
293    pub mode: String,
294    pub dry_run: bool,
295    pub paths_included: bool,
296    pub image_bytes_included: bool,
297    pub image_detail: String,
298    pub max_images: usize,
299    pub output_path: Option<String>,
300    pub markdown_path: Option<String>,
301    pub manifest_summary: AiAltManifestSummary,
302    pub sources: Vec<AiAltSource>,
303    pub selected_images: Vec<AiAltImageInput>,
304    pub skipped_image_count: usize,
305}
306
307#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
308pub struct AiAltManifestSummary {
309    pub config_path: String,
310    pub config_hash: String,
311    pub source_count: usize,
312    pub output_count: usize,
313    pub source_bytes: u64,
314    pub output_bytes: u64,
315}
316
317#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
318pub struct AiAltSource {
319    pub source_path: String,
320    pub source_hash: String,
321    pub source_width: u32,
322    pub source_height: u32,
323    pub source_bytes: u64,
324    pub representative_image_path: String,
325    pub representative_image_width: u32,
326    pub representative_image_height: u32,
327    pub representative_image_format: String,
328    pub image_bytes_included: bool,
329    pub image_detail: Option<String>,
330    pub variants: Vec<AiAltVariant>,
331}
332
333#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
334pub struct AiAltVariant {
335    pub output_path: String,
336    pub preset: String,
337    pub fit: String,
338    pub width: u32,
339    pub height: u32,
340    pub format: String,
341    pub bytes: u64,
342    pub hash: String,
343}
344
345#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
346pub struct AiAltImageInput {
347    pub source_path: String,
348    pub image_path: String,
349    pub mime_type: String,
350    pub width: u32,
351    pub height: u32,
352    pub bytes: u64,
353    pub hash: String,
354    pub detail: String,
355}
356
357#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
358pub struct AiAltProviderPayload {
359    #[serde(default)]
360    pub summary: String,
361    #[serde(default)]
362    pub drafts: Vec<AiAltDraft>,
363}
364
365#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
366pub struct AiAltDraft {
367    pub source_path: String,
368    pub representative_image_path: String,
369    pub candidate_alt_text: String,
370    pub review_note: String,
371    pub confidence: String,
372    pub image_category: String,
373    pub warnings: Vec<String>,
374}
375
376#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
377pub struct AiAltReport {
378    pub schema_version: u32,
379    pub provider: AiProvider,
380    pub model: String,
381    pub command: String,
382    pub config_path: String,
383    pub manifest_path: String,
384    pub project_root: String,
385    pub mode: String,
386    pub dry_run: bool,
387    pub paths_included: bool,
388    pub image_bytes_included: bool,
389    pub image_detail: String,
390    pub max_images: usize,
391    pub output_path: Option<String>,
392    pub markdown_path: Option<String>,
393    pub provider_called: bool,
394    pub summary: AiAltReportSummary,
395    pub sources: Vec<AiAltSource>,
396    pub selected_images: Vec<AiAltImageInput>,
397    pub provider_summary: String,
398    pub drafts: Vec<AiAltDraft>,
399}
400
401#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
402pub struct AiAltReportSummary {
403    pub source_count: usize,
404    pub output_count: usize,
405    pub selected_image_count: usize,
406    pub skipped_image_count: usize,
407    pub draft_count: usize,
408}
409
410#[derive(Debug, Clone, PartialEq, Eq)]
411pub struct MockAiReviewProviderClient {
412    provider: AiProvider,
413    fail: bool,
414}
415
416impl MockAiReviewProviderClient {
417    pub fn new(provider: AiProvider) -> Self {
418        Self {
419            provider,
420            fail: false,
421        }
422    }
423
424    pub fn failing(provider: AiProvider) -> Self {
425        Self {
426            provider,
427            fail: true,
428        }
429    }
430}
431
432impl AiReviewProviderClient for MockAiReviewProviderClient {
433    fn review(&self, request: &AiReviewRequest) -> Result<AiReviewProviderPayload> {
434        if self.fail {
435            return Err(crate::DevimgError::config(
436                &request.manifest_path,
437                "mock AI review provider failure",
438            ));
439        }
440
441        let first = request.outputs.first();
442        Ok(AiReviewProviderPayload {
443            summary: format!("mock {} AI review", self.provider.label()),
444            observations: first
445                .map(|output| {
446                    vec![AiReviewObservation {
447                        category: "format-quality concern".to_string(),
448                        severity: "advisory".to_string(),
449                        source_path: output.source_path.clone(),
450                        preset: output.preset.clone(),
451                        output_path: output.output_path.clone(),
452                        rationale: "Mock review observation for provider boundary tests."
453                            .to_string(),
454                        suggested_next_command: format!(
455                            "devimg review --manifest {} --output .devimg/review.html",
456                            request.manifest_path
457                        ),
458                    }]
459                })
460                .unwrap_or_default(),
461        })
462    }
463}
464
465#[derive(Debug, Clone, PartialEq, Eq)]
466pub struct MockAiAltProviderClient {
467    provider: AiProvider,
468    fail: bool,
469}
470
471impl MockAiAltProviderClient {
472    pub fn new(provider: AiProvider) -> Self {
473        Self {
474            provider,
475            fail: false,
476        }
477    }
478
479    pub fn failing(provider: AiProvider) -> Self {
480        Self {
481            provider,
482            fail: true,
483        }
484    }
485}
486
487impl AiAltProviderClient for MockAiAltProviderClient {
488    fn alt(&self, request: &AiAltRequest) -> Result<AiAltProviderPayload> {
489        if self.fail {
490            return Err(crate::DevimgError::config(
491                &request.config_path,
492                "mock AI alt provider failure",
493            ));
494        }
495
496        Ok(AiAltProviderPayload {
497            summary: format!("mock {} alt text", self.provider.label()),
498            drafts: request
499                .sources
500                .iter()
501                .map(|source| AiAltDraft {
502                    source_path: source.source_path.clone(),
503                    representative_image_path: source.representative_image_path.clone(),
504                    candidate_alt_text: "Mock draft alt text for provider boundary tests."
505                        .to_string(),
506                    review_note: "Review before using in application code.".to_string(),
507                    confidence: "medium".to_string(),
508                    image_category: "unknown".to_string(),
509                    warnings: vec!["needs-human-review".to_string()],
510                })
511                .collect(),
512        })
513    }
514}
515
516pub fn build_ai_consent_preview(
517    config: &Config,
518    options: &AiConsentOptions,
519) -> Result<AiConsentPreview> {
520    let manifest_path =
521        resolve_project_path_checked(config, &config.project.manifest, "manifest path")?;
522    let report_path = resolve_project_path_checked(config, &config.project.report, "report path")?;
523    let sources = scan_sources(config)?;
524    let source_files = sources
525        .into_iter()
526        .map(|source| AiSelectedFile {
527            source_name: source.source_name,
528            path: source.project_path,
529            role: "source-image".to_string(),
530            width: source.width,
531            height: source.height,
532            format: source.format.label().to_string(),
533            bytes: source.bytes,
534            hash: source.hash,
535            image_bytes_included: options.include_images,
536        })
537        .collect();
538
539    let mut manifest_readable = false;
540    let mut generated_outputs = Vec::new();
541    if let Ok(manifest) = read_manifest(&manifest_path) {
542        manifest_readable = true;
543        let mut seen = BTreeSet::new();
544        for output in manifest.outputs {
545            if seen.insert(output.output_path.clone()) {
546                generated_outputs.push(AiGeneratedOutput {
547                    source_path: output.source_path,
548                    output_path: output.output_path,
549                    preset: output.preset,
550                    fit: output.fit,
551                    width: output.width,
552                    height: output.height,
553                    format: output.format,
554                    bytes: output.bytes,
555                    hash: output.hash,
556                });
557            }
558        }
559        generated_outputs.sort_by(|left, right| left.output_path.cmp(&right.output_path));
560    }
561
562    Ok(AiConsentPreview {
563        provider: options.provider,
564        model: options.model.clone(),
565        command: options.command.clone(),
566        config_path: path_to_string(&options.config_path),
567        project_root: display_path(&config.project.root),
568        mode: if options.include_images {
569            "include-images".to_string()
570        } else {
571            "metadata-only".to_string()
572        },
573        dry_run: options.dry_run,
574        paths_included: true,
575        image_bytes_included: options.include_images,
576        output_path: options.output_path.as_deref().map(path_to_string),
577        manifest_path: path_to_string(&project_relative(config, &manifest_path)),
578        report_path: path_to_string(&project_relative(config, &report_path)),
579        manifest_readable,
580        source_files,
581        generated_outputs,
582    })
583}
584
585pub fn ai_consent_preview_to_json(preview: &AiConsentPreview) -> String {
586    serde_json::to_string_pretty(preview).expect("AI consent preview serialization cannot fail")
587        + "\n"
588}
589
590pub fn build_ai_review_request(manifest: &Manifest, options: &AiReviewOptions) -> AiReviewRequest {
591    let max_images = options.max_images.max(1);
592    let image_detail = options.image_detail.clone();
593    let mut outputs = manifest
594        .outputs
595        .iter()
596        .map(|output| AiReviewOutput {
597            source_path: output.source_path.clone(),
598            output_path: output.output_path.clone(),
599            preset: output.preset.clone(),
600            fit: output.fit.clone(),
601            width: output.width,
602            height: output.height,
603            format: output.format.clone(),
604            bytes: output.bytes,
605            hash: output.hash.clone(),
606            source_width: output.source_width,
607            source_height: output.source_height,
608            source_bytes: output.source_bytes,
609            image_bytes_included: false,
610            image_detail: None,
611        })
612        .collect::<Vec<_>>();
613    outputs.sort_by(|left, right| {
614        left.source_path
615            .cmp(&right.source_path)
616            .then(left.preset.cmp(&right.preset))
617            .then(left.width.cmp(&right.width))
618            .then(left.height.cmp(&right.height))
619            .then(left.format.cmp(&right.format))
620            .then(left.output_path.cmp(&right.output_path))
621    });
622
623    let selected_images = if options.include_images {
624        outputs
625            .iter()
626            .filter_map(|output| {
627                ai_image_mime_type(&output.format).map(|mime_type| AiReviewImageInput {
628                    output_path: output.output_path.clone(),
629                    mime_type: mime_type.to_string(),
630                    width: output.width,
631                    height: output.height,
632                    bytes: output.bytes,
633                    hash: output.hash.clone(),
634                    detail: image_detail.clone(),
635                })
636            })
637            .take(max_images)
638            .collect::<Vec<_>>()
639    } else {
640        Vec::new()
641    };
642    let selected_paths = selected_images
643        .iter()
644        .map(|image| image.output_path.clone())
645        .collect::<BTreeSet<_>>();
646    for output in &mut outputs {
647        if selected_paths.contains(&output.output_path) {
648            output.image_bytes_included = true;
649            output.image_detail = Some(image_detail.clone());
650        }
651    }
652
653    let output_count = manifest.outputs.len();
654    let skipped_image_count = if options.include_images {
655        output_count.saturating_sub(selected_images.len())
656    } else {
657        0
658    };
659    let mode = if options.include_images {
660        "include-images"
661    } else {
662        "metadata-only"
663    };
664
665    AiReviewRequest {
666        schema_version: 1,
667        provider: options.provider,
668        model: options.model.clone(),
669        command: options.command.clone(),
670        manifest_path: display_project_path(&options.project_root, &options.manifest_path),
671        project_root: display_path(&options.project_root),
672        mode: mode.to_string(),
673        dry_run: options.dry_run,
674        paths_included: true,
675        image_bytes_included: options.include_images,
676        image_detail,
677        max_images,
678        ai_output_path: options
679            .ai_output_path
680            .as_deref()
681            .map(|path| display_project_path(&options.project_root, path)),
682        markdown_path: options
683            .markdown_path
684            .as_deref()
685            .map(|path| display_project_path(&options.project_root, path)),
686        manifest_summary: AiReviewManifestSummary {
687            config_path: manifest.config_path.clone(),
688            config_hash: manifest.config_hash.clone(),
689            source_count: manifest_source_count(manifest),
690            output_count,
691            source_bytes: manifest.source_bytes_total(),
692            output_bytes: manifest.output_bytes_total(),
693        },
694        review_signals: manifest_quality_warnings(manifest),
695        outputs,
696        selected_images,
697        skipped_image_count,
698    }
699}
700
701pub fn build_ai_review_report(
702    request: &AiReviewRequest,
703    payload: AiReviewProviderPayload,
704    provider_called: bool,
705) -> AiReviewReport {
706    let observations = payload
707        .observations
708        .into_iter()
709        .map(normalize_ai_review_observation)
710        .collect::<Vec<_>>();
711    AiReviewReport {
712        schema_version: request.schema_version,
713        provider: request.provider,
714        model: request.model.clone(),
715        command: request.command.clone(),
716        manifest_path: request.manifest_path.clone(),
717        project_root: request.project_root.clone(),
718        mode: request.mode.clone(),
719        dry_run: request.dry_run,
720        paths_included: request.paths_included,
721        image_bytes_included: request.image_bytes_included,
722        image_detail: request.image_detail.clone(),
723        max_images: request.max_images,
724        ai_output_path: request.ai_output_path.clone(),
725        markdown_path: request.markdown_path.clone(),
726        provider_called,
727        summary: AiReviewSummary {
728            source_count: request.manifest_summary.source_count,
729            output_count: request.manifest_summary.output_count,
730            selected_image_count: request.selected_images.len(),
731            skipped_image_count: request.skipped_image_count,
732            review_signal_count: request.review_signals.len(),
733            observation_count: observations.len(),
734        },
735        review_signals: request.review_signals.clone(),
736        outputs: request.outputs.clone(),
737        selected_images: request.selected_images.clone(),
738        provider_summary: payload.summary,
739        observations,
740    }
741}
742
743pub fn build_ai_review_dry_run_report(request: &AiReviewRequest) -> AiReviewReport {
744    build_ai_review_report(
745        request,
746        AiReviewProviderPayload {
747            summary: "Dry run only; no provider call was made.".to_string(),
748            observations: Vec::new(),
749        },
750        false,
751    )
752}
753
754pub fn ai_review_report_to_json(report: &AiReviewReport) -> String {
755    serde_json::to_string_pretty(report).expect("AI review report serialization cannot fail") + "\n"
756}
757
758pub fn render_ai_review_markdown(report: &AiReviewReport) -> String {
759    let mut out = String::new();
760    out.push_str("# DevImg AI Review\n\n");
761    out.push_str("AI observations are advisory and must be reviewed by a human before changing source images or configuration.\n\n");
762    out.push_str("## Summary\n\n");
763    out.push_str(&format!("- Provider: `{}`\n", report.provider.label()));
764    out.push_str(&format!("- Model: `{}`\n", report.model));
765    out.push_str(&format!("- Mode: `{}`\n", report.mode));
766    out.push_str(&format!("- Dry run: `{}`\n", report.dry_run));
767    out.push_str(&format!(
768        "- Provider called: `{}`\n",
769        report.provider_called
770    ));
771    out.push_str(&format!("- Manifest: `{}`\n", report.manifest_path));
772    out.push_str(&format!(
773        "- Outputs reviewed: `{}`\n",
774        report.summary.output_count
775    ));
776    out.push_str(&format!(
777        "- Image inputs selected: `{}`\n",
778        report.summary.selected_image_count
779    ));
780    out.push_str(&format!(
781        "- Observations: `{}`\n\n",
782        report.summary.observation_count
783    ));
784
785    if !report.review_signals.is_empty() {
786        out.push_str("## Deterministic Signals\n\n");
787        for signal in &report.review_signals {
788            out.push_str(&format!("- {signal}\n"));
789        }
790        out.push('\n');
791    }
792
793    out.push_str("## Observations\n\n");
794    if report.observations.is_empty() {
795        out.push_str("No AI observations.\n");
796    } else {
797        for observation in &report.observations {
798            out.push_str(&format!("### {}\n\n", observation.category));
799            out.push_str(&format!("- Severity: `{}`\n", observation.severity));
800            out.push_str(&format!("- Source: `{}`\n", observation.source_path));
801            out.push_str(&format!("- Preset: `{}`\n", observation.preset));
802            out.push_str(&format!("- Output: `{}`\n", observation.output_path));
803            out.push_str(&format!("- Rationale: {}\n", observation.rationale));
804            out.push_str(&format!(
805                "- Suggested next command: `{}`\n\n",
806                observation.suggested_next_command
807            ));
808        }
809    }
810    out
811}
812
813pub fn build_ai_alt_request(manifest: &Manifest, options: &AiAltOptions) -> AiAltRequest {
814    let max_images = options.max_images.max(1);
815    let image_detail = options.image_detail.clone();
816    let mut grouped = BTreeMap::<String, AiAltSourceBuilder>::new();
817    for output in &manifest.outputs {
818        let source = grouped
819            .entry(output.source_path.clone())
820            .or_insert_with(|| AiAltSourceBuilder {
821                source_path: output.source_path.clone(),
822                source_hash: output.source_hash.clone(),
823                source_width: output.source_width,
824                source_height: output.source_height,
825                source_bytes: output.source_bytes,
826                variants: Vec::new(),
827            });
828        source.variants.push(AiAltVariant {
829            output_path: output.output_path.clone(),
830            preset: output.preset.clone(),
831            fit: output.fit.clone(),
832            width: output.width,
833            height: output.height,
834            format: output.format.clone(),
835            bytes: output.bytes,
836            hash: output.hash.clone(),
837        });
838    }
839
840    let mut selected_images = Vec::new();
841    let mut sources = Vec::new();
842    for mut builder in grouped.into_values() {
843        builder.variants.sort_by(|left, right| {
844            left.preset
845                .cmp(&right.preset)
846                .then(left.width.cmp(&right.width))
847                .then(left.height.cmp(&right.height))
848                .then(left.format.cmp(&right.format))
849                .then(left.output_path.cmp(&right.output_path))
850        });
851        let representative = builder.representative_image();
852        let mut image_bytes_included = false;
853        let mut image_detail_for_source = None;
854        if options.include_images && selected_images.len() < max_images {
855            if let Some(image) = representative.as_image_input(&builder.source_path, &image_detail)
856            {
857                image_bytes_included = true;
858                image_detail_for_source = Some(image_detail.clone());
859                selected_images.push(image);
860            }
861        }
862
863        sources.push(AiAltSource {
864            source_path: builder.source_path,
865            source_hash: builder.source_hash,
866            source_width: builder.source_width,
867            source_height: builder.source_height,
868            source_bytes: builder.source_bytes,
869            representative_image_path: representative.path,
870            representative_image_width: representative.width,
871            representative_image_height: representative.height,
872            representative_image_format: representative.format,
873            image_bytes_included,
874            image_detail: image_detail_for_source,
875            variants: builder.variants,
876        });
877    }
878
879    let skipped_image_count = if options.include_images {
880        sources.len().saturating_sub(selected_images.len())
881    } else {
882        0
883    };
884    let mode = if options.include_images {
885        "include-images"
886    } else {
887        "metadata-only"
888    };
889
890    AiAltRequest {
891        schema_version: 1,
892        provider: options.provider,
893        model: options.model.clone(),
894        command: options.command.clone(),
895        config_path: display_project_path(&options.project_root, &options.config_path),
896        manifest_path: display_project_path(&options.project_root, &options.manifest_path),
897        project_root: display_path(&options.project_root),
898        mode: mode.to_string(),
899        dry_run: options.dry_run,
900        paths_included: true,
901        image_bytes_included: options.include_images,
902        image_detail,
903        max_images,
904        output_path: options
905            .output_path
906            .as_deref()
907            .map(|path| display_project_path(&options.project_root, path)),
908        markdown_path: options
909            .markdown_path
910            .as_deref()
911            .map(|path| display_project_path(&options.project_root, path)),
912        manifest_summary: AiAltManifestSummary {
913            config_path: manifest.config_path.clone(),
914            config_hash: manifest.config_hash.clone(),
915            source_count: manifest_source_count(manifest),
916            output_count: manifest.outputs.len(),
917            source_bytes: manifest.source_bytes_total(),
918            output_bytes: manifest.output_bytes_total(),
919        },
920        sources,
921        selected_images,
922        skipped_image_count,
923    }
924}
925
926pub fn build_ai_alt_report(
927    request: &AiAltRequest,
928    payload: AiAltProviderPayload,
929    provider_called: bool,
930) -> AiAltReport {
931    let drafts = normalize_ai_alt_drafts(request, payload.drafts);
932    AiAltReport {
933        schema_version: request.schema_version,
934        provider: request.provider,
935        model: request.model.clone(),
936        command: request.command.clone(),
937        config_path: request.config_path.clone(),
938        manifest_path: request.manifest_path.clone(),
939        project_root: request.project_root.clone(),
940        mode: request.mode.clone(),
941        dry_run: request.dry_run,
942        paths_included: request.paths_included,
943        image_bytes_included: request.image_bytes_included,
944        image_detail: request.image_detail.clone(),
945        max_images: request.max_images,
946        output_path: request.output_path.clone(),
947        markdown_path: request.markdown_path.clone(),
948        provider_called,
949        summary: AiAltReportSummary {
950            source_count: request.sources.len(),
951            output_count: request.manifest_summary.output_count,
952            selected_image_count: request.selected_images.len(),
953            skipped_image_count: request.skipped_image_count,
954            draft_count: drafts.len(),
955        },
956        sources: request.sources.clone(),
957        selected_images: request.selected_images.clone(),
958        provider_summary: payload.summary,
959        drafts,
960    }
961}
962
963pub fn build_ai_alt_placeholder_report(request: &AiAltRequest) -> AiAltReport {
964    let drafts = request
965        .sources
966        .iter()
967        .map(|source| AiAltDraft {
968            source_path: source.source_path.clone(),
969            representative_image_path: source.representative_image_path.clone(),
970            candidate_alt_text: String::new(),
971            review_note: "Metadata-only placeholder; inspect the image and write human-reviewed alt text before application use.".to_string(),
972            confidence: "low".to_string(),
973            image_category: "unknown".to_string(),
974            warnings: vec!["needs-human-review".to_string()],
975        })
976        .collect();
977    build_ai_alt_report(
978        request,
979        AiAltProviderPayload {
980            summary: "Metadata-only placeholder; no provider call was made.".to_string(),
981            drafts,
982        },
983        false,
984    )
985}
986
987pub fn ai_alt_report_to_json(report: &AiAltReport) -> String {
988    serde_json::to_string_pretty(report).expect("AI alt report serialization cannot fail") + "\n"
989}
990
991pub fn render_ai_alt_markdown(report: &AiAltReport) -> String {
992    let mut out = String::new();
993    out.push_str("# DevImg Alt-Text Drafts\n\n");
994    out.push_str("Alt text is draft content and must be reviewed by a human before application use. DevImg does not insert this text into application code.\n\n");
995    out.push_str("## Summary\n\n");
996    out.push_str(&format!("- Provider: `{}`\n", report.provider.label()));
997    out.push_str(&format!("- Model: `{}`\n", report.model));
998    out.push_str(&format!("- Mode: `{}`\n", report.mode));
999    out.push_str(&format!("- Dry run: `{}`\n", report.dry_run));
1000    out.push_str(&format!(
1001        "- Provider called: `{}`\n",
1002        report.provider_called
1003    ));
1004    out.push_str(&format!("- Manifest: `{}`\n", report.manifest_path));
1005    out.push_str(&format!("- Sources: `{}`\n", report.summary.source_count));
1006    out.push_str(&format!(
1007        "- Image inputs selected: `{}`\n",
1008        report.summary.selected_image_count
1009    ));
1010    out.push_str(&format!("- Drafts: `{}`\n\n", report.summary.draft_count));
1011
1012    out.push_str("## Drafts\n\n");
1013    if report.drafts.is_empty() {
1014        out.push_str("No alt-text drafts.\n");
1015    } else {
1016        for draft in &report.drafts {
1017            out.push_str(&format!("### {}\n\n", draft.source_path));
1018            out.push_str(&format!(
1019                "- Representative image: `{}`\n",
1020                draft.representative_image_path
1021            ));
1022            out.push_str(&format!("- Category: `{}`\n", draft.image_category));
1023            out.push_str(&format!("- Confidence: `{}`\n", draft.confidence));
1024            out.push_str(&format!(
1025                "- Candidate alt text: {}\n",
1026                if draft.candidate_alt_text.is_empty() {
1027                    "_No draft generated in metadata-only mode._"
1028                } else {
1029                    draft.candidate_alt_text.as_str()
1030                }
1031            ));
1032            out.push_str(&format!("- Review note: {}\n", draft.review_note));
1033            if !draft.warnings.is_empty() {
1034                out.push_str(&format!("- Warnings: `{}`\n", draft.warnings.join("`, `")));
1035            }
1036            out.push('\n');
1037        }
1038    }
1039    out
1040}
1041
1042pub fn ai_image_mime_type(format: &str) -> Option<&'static str> {
1043    match format.to_ascii_lowercase().as_str() {
1044        "png" => Some("image/png"),
1045        "jpeg" | "jpg" => Some("image/jpeg"),
1046        "webp" => Some("image/webp"),
1047        "gif" => Some("image/gif"),
1048        _ => None,
1049    }
1050}
1051
1052#[derive(Debug, Clone, PartialEq, Eq)]
1053struct AiAltSourceBuilder {
1054    source_path: String,
1055    source_hash: String,
1056    source_width: u32,
1057    source_height: u32,
1058    source_bytes: u64,
1059    variants: Vec<AiAltVariant>,
1060}
1061
1062impl AiAltSourceBuilder {
1063    fn representative_image(&self) -> AiAltRepresentativeImage {
1064        let source_format = path_extension(&self.source_path);
1065        if ai_image_mime_type(&source_format).is_some() {
1066            return AiAltRepresentativeImage {
1067                path: self.source_path.clone(),
1068                width: self.source_width,
1069                height: self.source_height,
1070                format: source_format,
1071                bytes: self.source_bytes,
1072                hash: self.source_hash.clone(),
1073            };
1074        }
1075
1076        self.variants
1077            .iter()
1078            .filter(|variant| ai_image_mime_type(&variant.format).is_some())
1079            .max_by_key(|variant| u64::from(variant.width) * u64::from(variant.height))
1080            .map(|variant| AiAltRepresentativeImage {
1081                path: variant.output_path.clone(),
1082                width: variant.width,
1083                height: variant.height,
1084                format: variant.format.clone(),
1085                bytes: variant.bytes,
1086                hash: variant.hash.clone(),
1087            })
1088            .or_else(|| {
1089                self.variants
1090                    .first()
1091                    .map(|variant| AiAltRepresentativeImage {
1092                        path: variant.output_path.clone(),
1093                        width: variant.width,
1094                        height: variant.height,
1095                        format: variant.format.clone(),
1096                        bytes: variant.bytes,
1097                        hash: variant.hash.clone(),
1098                    })
1099            })
1100            .unwrap_or_else(|| AiAltRepresentativeImage {
1101                path: self.source_path.clone(),
1102                width: self.source_width,
1103                height: self.source_height,
1104                format: source_format,
1105                bytes: self.source_bytes,
1106                hash: self.source_hash.clone(),
1107            })
1108    }
1109}
1110
1111#[derive(Debug, Clone, PartialEq, Eq)]
1112struct AiAltRepresentativeImage {
1113    path: String,
1114    width: u32,
1115    height: u32,
1116    format: String,
1117    bytes: u64,
1118    hash: String,
1119}
1120
1121impl AiAltRepresentativeImage {
1122    fn as_image_input(&self, source_path: &str, detail: &str) -> Option<AiAltImageInput> {
1123        ai_image_mime_type(&self.format).map(|mime_type| AiAltImageInput {
1124            source_path: source_path.to_string(),
1125            image_path: self.path.clone(),
1126            mime_type: mime_type.to_string(),
1127            width: self.width,
1128            height: self.height,
1129            bytes: self.bytes,
1130            hash: self.hash.clone(),
1131            detail: detail.to_string(),
1132        })
1133    }
1134}
1135
1136fn display_path(path: &Path) -> String {
1137    let rendered = path_to_string(path);
1138    if rendered.is_empty() {
1139        ".".to_string()
1140    } else {
1141        rendered
1142    }
1143}
1144
1145fn display_project_path(project_root: &Path, path: &Path) -> String {
1146    let absolute = if path.is_absolute() {
1147        path.to_path_buf()
1148    } else {
1149        project_root.join(path)
1150    };
1151    absolute
1152        .strip_prefix(project_root)
1153        .map(path_to_string)
1154        .unwrap_or_else(|_| path_to_string(path))
1155}
1156
1157fn manifest_source_count(manifest: &Manifest) -> usize {
1158    manifest
1159        .outputs
1160        .iter()
1161        .map(|output| output.source_path.as_str())
1162        .collect::<BTreeSet<_>>()
1163        .len()
1164}
1165
1166fn path_extension(path: &str) -> String {
1167    Path::new(path)
1168        .extension()
1169        .and_then(|extension| extension.to_str())
1170        .unwrap_or("unknown")
1171        .to_ascii_lowercase()
1172}
1173
1174fn normalize_ai_review_observation(mut observation: AiReviewObservation) -> AiReviewObservation {
1175    observation.severity = "advisory".to_string();
1176    observation.category = normalize_observation_category(&observation.category).to_string();
1177    observation
1178}
1179
1180fn normalize_observation_category(category: &str) -> &'static str {
1181    match category {
1182        "crop risk" => "crop risk",
1183        "readability risk" => "readability risk",
1184        "excessive padding" => "excessive padding",
1185        "low-resolution source" => "low-resolution source",
1186        "format-quality concern" => "format-quality concern",
1187        "accessibility note" => "accessibility note",
1188        _ => "format-quality concern",
1189    }
1190}
1191
1192fn normalize_ai_alt_drafts(request: &AiAltRequest, drafts: Vec<AiAltDraft>) -> Vec<AiAltDraft> {
1193    let mut by_source = drafts
1194        .into_iter()
1195        .map(|mut draft| {
1196            draft.confidence = normalize_alt_confidence(&draft.confidence).to_string();
1197            draft.image_category = normalize_alt_category(&draft.image_category).to_string();
1198            draft.warnings = normalize_alt_warnings(draft.warnings);
1199            draft
1200        })
1201        .map(|draft| (draft.source_path.clone(), draft))
1202        .collect::<BTreeMap<_, _>>();
1203
1204    request
1205        .sources
1206        .iter()
1207        .map(|source| {
1208            let mut draft = by_source
1209                .remove(&source.source_path)
1210                .unwrap_or_else(|| AiAltDraft {
1211                    source_path: source.source_path.clone(),
1212                    representative_image_path: source.representative_image_path.clone(),
1213                    candidate_alt_text: String::new(),
1214                    review_note: "Provider did not return a draft for this source; write human-reviewed alt text manually.".to_string(),
1215                    confidence: "low".to_string(),
1216                    image_category: "unknown".to_string(),
1217                    warnings: vec!["needs-human-review".to_string()],
1218                });
1219            draft.source_path = source.source_path.clone();
1220            draft.representative_image_path = source.representative_image_path.clone();
1221            draft
1222        })
1223        .collect()
1224}
1225
1226fn normalize_alt_confidence(confidence: &str) -> &'static str {
1227    match confidence {
1228        "low" => "low",
1229        "medium" => "medium",
1230        "high" => "high",
1231        _ => "low",
1232    }
1233}
1234
1235fn normalize_alt_category(category: &str) -> &'static str {
1236    match category {
1237        "content-photo" => "content-photo",
1238        "screenshot" => "screenshot",
1239        "logo" => "logo",
1240        "illustration" => "illustration",
1241        "diagram" => "diagram",
1242        "icon" => "icon",
1243        "decorative" => "decorative",
1244        "text-heavy" => "text-heavy",
1245        "unknown" => "unknown",
1246        _ => "unknown",
1247    }
1248}
1249
1250fn normalize_alt_warnings(warnings: Vec<String>) -> Vec<String> {
1251    let mut normalized = warnings
1252        .into_iter()
1253        .map(|warning| match warning.as_str() {
1254            "decorative" => "decorative",
1255            "text-heavy" => "text-heavy",
1256            "logo" => "logo",
1257            "screenshot" => "screenshot",
1258            "uncertain-description" => "uncertain-description",
1259            "needs-human-review" => "needs-human-review",
1260            _ => "needs-human-review",
1261        })
1262        .map(ToString::to_string)
1263        .collect::<BTreeSet<_>>()
1264        .into_iter()
1265        .collect::<Vec<_>>();
1266    if normalized.is_empty() {
1267        normalized.push("needs-human-review".to_string());
1268    }
1269    normalized
1270}
1271
1272#[cfg(test)]
1273mod tests {
1274    use std::path::PathBuf;
1275
1276    use super::{
1277        ai_alt_report_to_json, ai_consent_preview_to_json, ai_image_mime_type,
1278        ai_review_report_to_json, build_ai_alt_placeholder_report, build_ai_alt_report,
1279        build_ai_alt_request, build_ai_review_dry_run_report, build_ai_review_report,
1280        build_ai_review_request, render_ai_alt_markdown, render_ai_review_markdown, AiAltOptions,
1281        AiAltProviderClient, AiConsentPreview, AiGeneratedOutput, AiProvider, AiProviderClient,
1282        AiReviewOptions, AiReviewProviderClient, AiSelectedFile, MockAiAltProviderClient,
1283        MockAiProviderClient, MockAiReviewProviderClient,
1284    };
1285    use crate::manifest::{Manifest, ManifestOutput};
1286
1287    #[test]
1288    fn provider_labels_and_env_vars_are_stable() {
1289        assert_eq!(AiProvider::Openai.label(), "openai");
1290        assert_eq!(AiProvider::Openai.credential_env_var(), "OPENAI_API_KEY");
1291        assert_eq!(AiProvider::Anthropic.label(), "anthropic");
1292        assert_eq!(
1293            AiProvider::Anthropic.credential_env_var(),
1294            "ANTHROPIC_API_KEY"
1295        );
1296    }
1297
1298    #[test]
1299    fn mock_provider_client_returns_stable_non_network_response() {
1300        let preview = AiConsentPreview {
1301            provider: AiProvider::Openai,
1302            model: "test-model".to_string(),
1303            command: "devimg ai consent".to_string(),
1304            config_path: "devimg.toml".to_string(),
1305            project_root: ".".to_string(),
1306            mode: "metadata-only".to_string(),
1307            dry_run: true,
1308            paths_included: true,
1309            image_bytes_included: false,
1310            output_path: None,
1311            manifest_path: "public/images/devimg-manifest.json".to_string(),
1312            report_path: "devimg-report.md".to_string(),
1313            manifest_readable: false,
1314            source_files: vec![AiSelectedFile {
1315                source_name: "portfolio".to_string(),
1316                path: "assets/images/sample.png".to_string(),
1317                role: "source-image".to_string(),
1318                width: 100,
1319                height: 50,
1320                format: "png".to_string(),
1321                bytes: 12,
1322                hash: "blake3:source".to_string(),
1323                image_bytes_included: false,
1324            }],
1325            generated_outputs: vec![AiGeneratedOutput {
1326                source_path: "assets/images/sample.png".to_string(),
1327                output_path: "public/images/generated/sample.webp".to_string(),
1328                preset: "card".to_string(),
1329                fit: "cover".to_string(),
1330                width: 64,
1331                height: 36,
1332                format: "webp".to_string(),
1333                bytes: 10,
1334                hash: "blake3:output".to_string(),
1335            }],
1336        };
1337
1338        let response = MockAiProviderClient::new(AiProvider::Anthropic).consent_response(&preview);
1339
1340        assert_eq!(response.provider, AiProvider::Anthropic);
1341        assert_eq!(response.model, "test-model");
1342        assert_eq!(response.request_kind, "consent-preview");
1343        assert!(!response.network_called);
1344        assert_eq!(response.selected_file_count, 1);
1345        assert_eq!(response.generated_output_count, 1);
1346    }
1347
1348    #[test]
1349    fn consent_preview_json_is_timestamp_free() {
1350        let preview = AiConsentPreview {
1351            provider: AiProvider::Anthropic,
1352            model: "stable-model".to_string(),
1353            command: "devimg ai consent".to_string(),
1354            config_path: "devimg.toml".to_string(),
1355            project_root: ".".to_string(),
1356            mode: "metadata-only".to_string(),
1357            dry_run: true,
1358            paths_included: true,
1359            image_bytes_included: false,
1360            output_path: Some("/tmp/consent.json".to_string()),
1361            manifest_path: "public/images/devimg-manifest.json".to_string(),
1362            report_path: "devimg-report.md".to_string(),
1363            manifest_readable: false,
1364            source_files: Vec::new(),
1365            generated_outputs: Vec::new(),
1366        };
1367
1368        let json = ai_consent_preview_to_json(&preview);
1369
1370        assert!(json.contains("\"provider\": \"anthropic\""));
1371        assert!(json.contains("\"model\": \"stable-model\""));
1372        assert!(!json.contains("generated_at"));
1373        assert!(!json.contains("timestamp"));
1374    }
1375
1376    #[test]
1377    fn ai_review_request_selects_metadata_and_image_inputs() {
1378        let manifest = sample_manifest();
1379        let request = build_ai_review_request(
1380            &manifest,
1381            &AiReviewOptions {
1382                provider: AiProvider::Openai,
1383                model: "vision-model".to_string(),
1384                command: "devimg review --ai".to_string(),
1385                manifest_path: PathBuf::from("/repo/public/images/devimg-manifest.json"),
1386                project_root: PathBuf::from("/repo"),
1387                dry_run: true,
1388                include_images: true,
1389                image_detail: "low".to_string(),
1390                max_images: 1,
1391                ai_output_path: Some(PathBuf::from("/repo/devimg-ai-review.json")),
1392                markdown_path: Some(PathBuf::from("/tmp/devimg-ai-review.md")),
1393            },
1394        );
1395
1396        assert_eq!(request.provider, AiProvider::Openai);
1397        assert_eq!(request.mode, "include-images");
1398        assert_eq!(request.manifest_path, "public/images/devimg-manifest.json");
1399        assert_eq!(
1400            request.ai_output_path.as_deref(),
1401            Some("devimg-ai-review.json")
1402        );
1403        assert_eq!(
1404            request.markdown_path.as_deref(),
1405            Some("/tmp/devimg-ai-review.md")
1406        );
1407        assert_eq!(request.manifest_summary.source_count, 1);
1408        assert_eq!(request.manifest_summary.output_count, 2);
1409        assert_eq!(request.outputs.len(), 2);
1410        assert_eq!(request.selected_images.len(), 1);
1411        assert_eq!(request.selected_images[0].mime_type, "image/webp");
1412        let webp_output = request
1413            .outputs
1414            .iter()
1415            .find(|output| output.format == "webp")
1416            .expect("webp output exists");
1417        let avif_output = request
1418            .outputs
1419            .iter()
1420            .find(|output| output.format == "avif")
1421            .expect("avif output exists");
1422        assert!(webp_output.image_bytes_included);
1423        assert!(!avif_output.image_bytes_included);
1424        assert_eq!(request.skipped_image_count, 1);
1425    }
1426
1427    #[test]
1428    fn ai_review_dry_run_json_and_markdown_are_timestamp_free() {
1429        let manifest = sample_manifest();
1430        let request = build_ai_review_request(
1431            &manifest,
1432            &AiReviewOptions {
1433                provider: AiProvider::Openai,
1434                model: "dry-run-model".to_string(),
1435                command: "devimg review --ai".to_string(),
1436                manifest_path: PathBuf::from("public/images/devimg-manifest.json"),
1437                project_root: PathBuf::from("."),
1438                dry_run: true,
1439                include_images: false,
1440                image_detail: "low".to_string(),
1441                max_images: 8,
1442                ai_output_path: None,
1443                markdown_path: None,
1444            },
1445        );
1446        let report = build_ai_review_dry_run_report(&request);
1447        let json = ai_review_report_to_json(&report);
1448        let markdown = render_ai_review_markdown(&report);
1449
1450        assert!(json.contains("\"provider\": \"openai\""));
1451        assert!(json.contains("\"dry_run\": true"));
1452        assert!(json.contains("\"provider_called\": false"));
1453        assert!(!json.contains("generated_at"));
1454        assert!(!json.contains("timestamp"));
1455        assert!(markdown.contains("# DevImg AI Review"));
1456        assert!(markdown.contains("Dry run: `true`"));
1457    }
1458
1459    #[test]
1460    fn mock_ai_review_provider_returns_stable_payload_and_failure() {
1461        let manifest = sample_manifest();
1462        let request = build_ai_review_request(
1463            &manifest,
1464            &AiReviewOptions {
1465                provider: AiProvider::Anthropic,
1466                model: "mock-model".to_string(),
1467                command: "devimg review --ai".to_string(),
1468                manifest_path: PathBuf::from("public/images/devimg-manifest.json"),
1469                project_root: PathBuf::from("."),
1470                dry_run: false,
1471                include_images: false,
1472                image_detail: "low".to_string(),
1473                max_images: 8,
1474                ai_output_path: None,
1475                markdown_path: None,
1476            },
1477        );
1478
1479        let payload = MockAiReviewProviderClient::new(AiProvider::Anthropic)
1480            .review(&request)
1481            .expect("mock provider succeeds");
1482        let report = build_ai_review_report(&request, payload, true);
1483
1484        assert!(report.provider_called);
1485        assert_eq!(report.provider_summary, "mock anthropic AI review");
1486        assert_eq!(report.observations.len(), 1);
1487        assert_eq!(report.observations[0].severity, "advisory");
1488
1489        let error = MockAiReviewProviderClient::failing(AiProvider::Openai)
1490            .review(&request)
1491            .expect_err("mock provider fails");
1492        assert!(error
1493            .to_string()
1494            .contains("mock AI review provider failure"));
1495    }
1496
1497    #[test]
1498    fn ai_alt_request_groups_sources_and_selects_representative_images() {
1499        let manifest = sample_manifest();
1500        let request = build_ai_alt_request(
1501            &manifest,
1502            &AiAltOptions {
1503                provider: AiProvider::Openai,
1504                model: "alt-model".to_string(),
1505                command: "devimg alt".to_string(),
1506                config_path: PathBuf::from("/repo/devimg.toml"),
1507                manifest_path: PathBuf::from("/repo/public/images/devimg-manifest.json"),
1508                project_root: PathBuf::from("/repo"),
1509                dry_run: true,
1510                include_images: true,
1511                image_detail: "low".to_string(),
1512                max_images: 1,
1513                output_path: Some(PathBuf::from("/repo/devimg-alt.json")),
1514                markdown_path: Some(PathBuf::from("/tmp/devimg-alt.md")),
1515            },
1516        );
1517
1518        assert_eq!(request.provider, AiProvider::Openai);
1519        assert_eq!(request.mode, "include-images");
1520        assert_eq!(request.config_path, "devimg.toml");
1521        assert_eq!(request.manifest_path, "public/images/devimg-manifest.json");
1522        assert_eq!(request.output_path.as_deref(), Some("devimg-alt.json"));
1523        assert_eq!(request.markdown_path.as_deref(), Some("/tmp/devimg-alt.md"));
1524        assert_eq!(request.sources.len(), 1);
1525        assert_eq!(request.sources[0].variants.len(), 2);
1526        assert_eq!(
1527            request.sources[0].representative_image_path,
1528            "assets/images/sample.png"
1529        );
1530        assert!(request.sources[0].image_bytes_included);
1531        assert_eq!(request.selected_images.len(), 1);
1532        assert_eq!(request.selected_images[0].mime_type, "image/png");
1533        assert_eq!(request.skipped_image_count, 0);
1534    }
1535
1536    #[test]
1537    fn ai_alt_placeholder_json_and_markdown_are_timestamp_free() {
1538        let manifest = sample_manifest();
1539        let request = build_ai_alt_request(
1540            &manifest,
1541            &AiAltOptions {
1542                provider: AiProvider::Openai,
1543                model: "dry-run-model".to_string(),
1544                command: "devimg alt".to_string(),
1545                config_path: PathBuf::from("devimg.toml"),
1546                manifest_path: PathBuf::from("public/images/devimg-manifest.json"),
1547                project_root: PathBuf::from("."),
1548                dry_run: true,
1549                include_images: false,
1550                image_detail: "low".to_string(),
1551                max_images: 8,
1552                output_path: None,
1553                markdown_path: None,
1554            },
1555        );
1556        let report = build_ai_alt_placeholder_report(&request);
1557        let json = ai_alt_report_to_json(&report);
1558        let markdown = render_ai_alt_markdown(&report);
1559
1560        assert!(json.contains("\"provider\": \"openai\""));
1561        assert!(json.contains("\"provider_called\": false"));
1562        assert!(json.contains("\"candidate_alt_text\": \"\""));
1563        assert!(!json.contains("generated_at"));
1564        assert!(!json.contains("timestamp"));
1565        assert!(markdown.contains("# DevImg Alt-Text Drafts"));
1566        assert!(markdown.contains("Provider called: `false`"));
1567        assert!(markdown.contains("_No draft generated in metadata-only mode._"));
1568    }
1569
1570    #[test]
1571    fn mock_ai_alt_provider_returns_stable_payload_and_failure() {
1572        let manifest = sample_manifest();
1573        let request = build_ai_alt_request(
1574            &manifest,
1575            &AiAltOptions {
1576                provider: AiProvider::Anthropic,
1577                model: "mock-model".to_string(),
1578                command: "devimg alt".to_string(),
1579                config_path: PathBuf::from("devimg.toml"),
1580                manifest_path: PathBuf::from("public/images/devimg-manifest.json"),
1581                project_root: PathBuf::from("."),
1582                dry_run: false,
1583                include_images: false,
1584                image_detail: "low".to_string(),
1585                max_images: 8,
1586                output_path: None,
1587                markdown_path: None,
1588            },
1589        );
1590
1591        let payload = MockAiAltProviderClient::new(AiProvider::Anthropic)
1592            .alt(&request)
1593            .expect("mock provider succeeds");
1594        let report = build_ai_alt_report(&request, payload, true);
1595
1596        assert!(report.provider_called);
1597        assert_eq!(report.provider_summary, "mock anthropic alt text");
1598        assert_eq!(report.drafts.len(), 1);
1599        assert_eq!(report.drafts[0].confidence, "medium");
1600        assert_eq!(report.drafts[0].warnings, vec!["needs-human-review"]);
1601
1602        let error = MockAiAltProviderClient::failing(AiProvider::Openai)
1603            .alt(&request)
1604            .expect_err("mock provider fails");
1605        assert!(error.to_string().contains("mock AI alt provider failure"));
1606    }
1607
1608    #[test]
1609    fn ai_image_mime_type_matches_openai_supported_inputs() {
1610        assert_eq!(ai_image_mime_type("png"), Some("image/png"));
1611        assert_eq!(ai_image_mime_type("jpeg"), Some("image/jpeg"));
1612        assert_eq!(ai_image_mime_type("jpg"), Some("image/jpeg"));
1613        assert_eq!(ai_image_mime_type("webp"), Some("image/webp"));
1614        assert_eq!(ai_image_mime_type("gif"), Some("image/gif"));
1615        assert_eq!(ai_image_mime_type("avif"), None);
1616    }
1617
1618    fn sample_manifest() -> Manifest {
1619        Manifest {
1620            version: 1,
1621            generated_at: "unix:123".to_string(),
1622            config_path: "devimg.toml".to_string(),
1623            config_hash: "blake3:config".to_string(),
1624            outputs: vec![
1625                ManifestOutput {
1626                    source_path: "assets/images/sample.png".to_string(),
1627                    source_hash: "blake3:source".to_string(),
1628                    source_width: 100,
1629                    source_height: 80,
1630                    source_bytes: 1000,
1631                    output_path: "public/images/generated/sample.project-card.64.webp".to_string(),
1632                    preset: "project-card".to_string(),
1633                    fit: "cover".to_string(),
1634                    width: 64,
1635                    height: 64,
1636                    format: "webp".to_string(),
1637                    bytes: 700,
1638                    hash: "blake3:webp".to_string(),
1639                    operation_hash: "blake3:operation-webp".to_string(),
1640                },
1641                ManifestOutput {
1642                    source_path: "assets/images/sample.png".to_string(),
1643                    source_hash: "blake3:source".to_string(),
1644                    source_width: 100,
1645                    source_height: 80,
1646                    source_bytes: 1000,
1647                    output_path: "public/images/generated/sample.project-card.64.avif".to_string(),
1648                    preset: "project-card".to_string(),
1649                    fit: "cover".to_string(),
1650                    width: 64,
1651                    height: 64,
1652                    format: "avif".to_string(),
1653                    bytes: 600,
1654                    hash: "blake3:avif".to_string(),
1655                    operation_hash: "blake3:operation-avif".to_string(),
1656                },
1657            ],
1658        }
1659    }
1660}