//! Dogfooding corpus regression tests for Milestone 45.

use std::fs;
use std::path::Path;

use index_extract::{ExtractFormat, extract_document, validate_document_json_schema};
use index_renderer::{RenderOptions, render_document};
use index_transformer::{Transformer, state::Empty};

fn transform(html: &str) -> index_core::IndexDocument {
    Transformer::<Empty>::new()
        .fetched(html)
        .parse()
        .extract()
        .transform()
        .into_document()
}

#[test]
fn committed_dogfooding_corpus_transforms_renders_and_extracts()
-> Result<(), Box<dyn std::error::Error>> {
    let manifest = include_str!("../../../docs/dogfooding/corpus.tsv");
    let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
    let mut count = 0;

    for line in manifest.lines() {
        if line.trim().is_empty() || line.starts_with('#') {
            continue;
        }

        let fields = line.split('\t').collect::<Vec<_>>();
        assert_eq!(fields.len(), 6, "invalid dogfooding corpus row: {line}");

        let id = fields[0];
        let tier = fields[2];
        let path = fields[3];
        let expected_path = fields[4];
        assert!(matches!(tier, "0" | "1" | "2" | "3" | "4" | "5"));
        assert!(matches!(expected_path, "generic" | "adapter" | "failure"));

        let html = fs::read_to_string(workspace_root.join(path))?;
        let document = transform(&html);
        let rendered = render_document(&document, RenderOptions::default());
        let markdown = extract_document(&document, ExtractFormat::Markdown);
        let json = extract_document(&document, ExtractFormat::Json);

        assert!(!document.title.trim().is_empty(), "{id} has empty title");
        assert!(!rendered.trim().is_empty(), "{id} rendered empty output");
        assert!(!markdown.trim().is_empty(), "{id} emitted empty markdown");
        assert!(
            validate_document_json_schema(&json).is_ok(),
            "{id} emitted invalid JSON"
        );
        if expected_path == "adapter" {
            assert!(
                document.metadata.adapter_id.is_some(),
                "{id} expected adapter output"
            );
        }
        count += 1;
    }

    assert!(count >= 8, "dogfooding corpus is too small: {count}");
    Ok(())
}
