//! Doctor view — run `envseal doctor` and surface the system security
//! report inline.
//!
//! Doctor is a read-only diagnostic command that audits the host
//! (loader env, hardware tier, GUI sanity, file permissions, etc) and
//! does not touch secrets — perfectly suitable for a one-click button.

use std::path::PathBuf;

use eframe::egui;

fn resolve_envseal_cli() -> PathBuf {
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            let mut candidate = dir.join("envseal");
            #[cfg(windows)]
            {
                candidate.set_extension("exe");
            }
            if candidate.is_file() {
                return candidate;
            }
        }
    }
    PathBuf::from("envseal")
}

#[derive(Default)]
pub struct DoctorState {
    pub result_text: Option<String>,
    pub success: Option<bool>,
}

pub fn render(ui: &mut egui::Ui, state: &mut DoctorState) {
    ui.add_space(8.0);
    ui.horizontal(|ui| {
        ui.heading("Doctor");
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            let btn = ui.add(
                egui::Button::new("Run Check")
                    .fill(egui::Color32::from_rgb(0xe4, 0xe4, 0xe7))
                    .min_size(egui::vec2(100.0, 30.0))
                    .corner_radius(8.0),
            );
            if btn.clicked() {
                let mut cmd = std::process::Command::new(resolve_envseal_cli());
                cmd.arg("doctor");
                match cmd.output() {
                    Ok(output) => {
                        let out = String::from_utf8_lossy(&output.stdout).to_string();
                        let err = String::from_utf8_lossy(&output.stderr).to_string();
                        let combined = if err.is_empty() {
                            out
                        } else if out.is_empty() {
                            err
                        } else {
                            format!("{out}\n{err}")
                        };
                        state.success = Some(output.status.success());
                        state.result_text = Some(combined);
                    }
                    Err(e) => {
                        state.success = Some(false);
                        state.result_text = Some(format!("Failed to run doctor: {e}"));
                    }
                }
            }
        });
    });
    ui.add_space(4.0);
    ui.label(
        egui::RichText::new(
            "System security audit — hardware tier, loader environment, file permissions.",
        )
        .weak(),
    );
    ui.add_space(12.0);

    match (&state.result_text, state.success) {
        (None, _) => {
            ui.add_space(30.0);
            ui.vertical_centered(|ui| {
                ui.label(egui::RichText::new("🩺").size(36.0));
                ui.label("No diagnostic yet");
                ui.label(egui::RichText::new("Click Run Check to audit this machine.").weak());
            });
        }
        (Some(text), Some(true)) => {
            egui::Frame::new()
                .fill(egui::Color32::from_rgba_premultiplied(6, 78, 59, 40))
                .corner_radius(8.0)
                .inner_margin(12.0)
                .show(ui, |ui| {
                    ui.label(
                        egui::RichText::new("System OK")
                            .color(egui::Color32::from_rgb(0x22, 0xc5, 0x5e))
                            .size(15.0),
                    );
                });
            ui.add_space(8.0);
            egui::ScrollArea::vertical().show(ui, |ui| {
                ui.label(egui::RichText::new(text).size(12.0).monospace());
            });
        }
        (Some(text), _) => {
            egui::Frame::new()
                .fill(egui::Color32::from_rgba_premultiplied(127, 29, 29, 40))
                .corner_radius(8.0)
                .inner_margin(12.0)
                .show(ui, |ui| {
                    ui.label(
                        egui::RichText::new("Issues detected")
                            .color(egui::Color32::from_rgb(239, 68, 68))
                            .size(15.0),
                    );
                });
            ui.add_space(8.0);
            egui::ScrollArea::vertical().show(ui, |ui| {
                ui.label(egui::RichText::new(text).size(12.0).monospace());
            });
        }
    }
}
