// THROWAWAY (not committed as a test): copy to crates/core/tests/zz_frame_probe.rs, run
// `FRAME_OUT=<empty dir> cargo test -p faunosteo-core --test zz_frame_probe -- --nocapture`, delete it.
// Each case: the composed canvas, the preview box, the core's f64 expectation of every visible disc
// (size and centre in CSS px relative to the svg box), and the core's verdict on the frame.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use common::sheet_readers::{OPEN, document};
use faunosteo_core::anatomy::compose::compose_canvas;
use faunosteo_core::anatomy::frame::{DETAIL_PREVIEW_PX, MAIN_PREVIEW_PX, frame_faults, view_frame, FrameFault, Placement};
use faunosteo_core::anatomy::layer::twin_radius;
use faunosteo_core::anatomy::svg::{Element, read_svg, serialize::serialize};
use faunosteo_core::domain::sheet::{AnatomicalSheetDocument, Annotation, Geometry};
use serde::Deserialize;
use serde_json::{Value, json};

fn doc_of(text: &str) -> AnatomicalSheetDocument {
    AnatomicalSheetDocument::deserialize(serde_json::from_str::<Value>(text).unwrap()).unwrap()
}

fn write(name: &str, doc: &AnatomicalSheetDocument, view: &str, root: &Element, raw: Option<[f64; 4]>) {
    let out = std::env::var("FRAME_OUT").unwrap();
    let v = doc.views.iter().find(|v| v.id() == view).unwrap();
    let frame = raw.unwrap_or_else(|| { let f = view_frame(v, root).unwrap(); [f.min_x, f.min_y, f.width, f.height] });
    let (bw, bh) = if v.is_main() { MAIN_PREVIEW_PX } else { DETAIL_PREVIEW_PX };
    let scale = (bw / frame[2]).min(bh / frame[3]);
    let faults = frame_faults(doc, |_| Some(root));
    let core = if faults.iter().any(|f| matches!(f, FrameFault::NoFrame { .. })) { "no_frame" }
        else if faults.iter().any(|f| matches!(f, FrameFault::Annotation { placement: Placement::TooSmall, .. })) { "too_small" }
        else if faults.is_empty() { "accepted" } else { "out_of_frame" };
    let mut svg = serialize(&compose_canvas(doc, view, root).unwrap());
    if let Some(r) = raw {
        let vb = svg[..svg.find('>').unwrap()].to_owned();
        let start = vb.find("viewBox=\"").unwrap() + 9;
        let end = start + vb[start..].find('"').unwrap();
        svg.replace_range(start..end, &format!("{} {} {} {}", r[0], r[1], r[2], r[3]));
    }
    let markers: Vec<Value> = doc.annotations.iter().filter(|a| a.view_id() == view).filter_map(|a| match a {
        Annotation::Observable(o) => match o.geometry.as_ref()? { Geometry::Circle(c) => Some(json!({
            "id": o.id, "size": 2.0 * twin_radius(c.r) * scale, "hitbox": 2.0 * c.r * scale,
            "cx": (c.cx - frame[0]) * scale, "cy": (c.cy - frame[1]) * scale })), _ => None },
        _ => None }).collect();
    std::fs::write(format!("{out}/{name}.json"), json!({ "name": name, "box": [bw, bh], "core": core, "svg": svg, "markers": markers }).to_string()).unwrap();
}

fn shared(view_box: &str, cx: f64, cy: f64, r: f64) -> (AnatomicalSheetDocument, Element) {
    let mut doc: Value = serde_json::from_str(&document()).unwrap();
    doc["annotations"][0]["geometry"] = json!({ "type": "circle", "cx": cx, "cy": cy, "r": r });
    let text = OPEN.replace("0 0 10 10", view_box) + "<path d=\"M0 0h1\"/></svg>";
    (doc_of(&doc.to_string()), read_svg(&text).unwrap().root)
}

fn scaled_horse(factor: f64) -> Element {
    let horse = common::repo_file("supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg");
    let text = horse.replacen("viewBox=\"0 0 2073.4 1629.4\">", &format!("viewBox=\"0 0 {} {}\"><g transform=\"scale({factor})\">", 2073.4 * factor, 1629.4 * factor), 1).replacen("</svg>", "</g></svg>", 1);
    read_svg(&text).unwrap().root
}

#[test]
fn write_cases() {
    let equine = doc_of(&common::repo_file("supabase/seed/anatomical-sheets/equine/draft/document.json"));
    for (name, factor) in [("a-equine-main", 1.0), ("b-equine-x1.24", 1.24), ("c-equine-x1.25", 1.25), ("c2-equine-x100", 100.0)] {
        write(name, &equine, "main", &scaled_horse(factor), None);
    }
    write("d-equine-head-detail-box", &equine, "head", &scaled_horse(1.0), None);
    let m = 1_048_576.0 - 8192.0;
    let (d, r) = shared(&format!("{m} 0 8192 8192"), m + 4096.37, 4100.63, 200.0);
    write("e-edge-magnitude-2^20", &d, "main", &r, None);
    let (d, r) = shared("2550 0 10 10", 2555.37, 5.63, 1.0);
    write("f-offset-ratio-256", &d, "main", &r, None);
    let (d, r) = shared("1000000 0 10 10", 1_000_005.37, 5.63, 1.0);
    write("g-offset-ratio-1e5-refused", &d, "main", &r, Some([1e6, 0.0, 10.0, 10.0]));
    let (d, r) = shared("10000000 0 10 10", 10_000_005.37, 5.63, 1.0);
    write("h-offset-ratio-1e6-refused", &d, "main", &r, Some([1e7, 0.0, 10.0, 10.0]));
    let s = 1.0 / 1_048_576.0;
    let (d, r) = shared(&format!("0 0 {s} {s}"), s * 0.537, s * 0.463, s / 4.0);
    write("i-span-2^-20", &d, "main", &r, None);
    let (d, r) = shared("0 0 1e-30 1e-30", 0.537e-30, 0.463e-30, 0.25e-30);
    write("j-span-1e-30-refused", &d, "main", &r, Some([0.0, 0.0, 1e-30, 1e-30]));
    // Span series, the point's hitbox a quarter of the span (its disc stays 4 units across).
    for (label, span) in [("1", 1.0), ("2^-3", 0.125), ("2^-5", 0.03125), ("2^-7", 0.0078125), ("2^-10", 1.0 / 1024.0), ("2^-14", 1.0 / 16384.0)] {
        let (d, r) = shared(&format!("0 0 {span} {span}"), span * 0.537, span * 0.463, span / 4.0);
        write(&format!("m-span-{label}"), &d, "main", &r, None);
    }
    let (d, r) = shared("0 0 1000 1000", 500.37, 499.63, 20.0);
    write("k-threshold-4.58px", &d, "main", &r, None);
    let (d, r) = shared("0 0 1000 1000", 500.37, 499.63, 18.0);
    write("l-threshold-3.43px", &d, "main", &r, None);
}
