use std::collections::HashMap;
use std::io::Cursor;

use fw_file::dcm::{CreateDicomValue, create_dcm_as_bytes, is_dicom_part10};

fn valid_part10_bytes() -> Vec<u8> {
    let tags = HashMap::from([
        ("PatientID", CreateDicomValue::from("TEST001".to_string())),
        (
            "PatientName",
            CreateDicomValue::from("Test^Patient".to_string()),
        ),
    ]);
    create_dcm_as_bytes(tags)
        .expect("Failed to create DICOM")
        .into_inner()
}

#[test]
fn test_is_dicom_part10_valid_file() {
    let bytes = valid_part10_bytes();
    let mut cursor = Cursor::new(&bytes);
    assert!(is_dicom_part10(&mut cursor).unwrap());
}

#[test]
fn test_is_dicom_part10_restores_reader_position() {
    let bytes = valid_part10_bytes();
    let mut cursor = Cursor::new(&bytes);
    is_dicom_part10(&mut cursor).unwrap();
    assert_eq!(
        cursor.position(),
        0,
        "Reader position should be restored to 0"
    );
}

#[test]
fn test_is_dicom_part10_no_dicm_magic() {
    // 132 bytes of zeros — valid length but no DICM magic at offset 128
    let bytes = vec![0u8; 256];
    let mut cursor = Cursor::new(&bytes);
    assert!(!is_dicom_part10(&mut cursor).unwrap());
}

#[test]
fn test_is_dicom_part10_too_short() {
    let bytes = vec![0u8; 64];
    let mut cursor = Cursor::new(&bytes);
    assert!(!is_dicom_part10(&mut cursor).unwrap());
}

#[test]
fn test_is_dicom_part10_dicm_magic_but_corrupt_meta() {
    // Preamble + DICM magic, then garbage bytes instead of a valid meta group
    let mut bytes = vec![0u8; 128];
    bytes.extend_from_slice(b"DICM");
    bytes.extend_from_slice(&[0xFF; 128]); // corrupt meta group
    let mut cursor = Cursor::new(&bytes);
    assert!(!is_dicom_part10(&mut cursor).unwrap());
}

#[test]
fn test_is_dicom_part10_raw_dicom_no_preamble() {
    // Raw DICOM starting directly with tag (0008,0016) — no preamble, no DICM
    // Tag group 0x0008 little-endian, element 0x0016 little-endian, VR "UI", length 26
    let mut bytes = Vec::new();
    bytes.extend_from_slice(&[0x08, 0x00, 0x16, 0x00]); // tag (0008,0016)
    bytes.extend_from_slice(b"UI"); // VR
    bytes.extend_from_slice(&[0x1A, 0x00]); // length 26
    bytes.extend_from_slice(b"1.2.840.10008.5.1.4.1.1.2\0"); // value
    let mut cursor = Cursor::new(&bytes);
    assert!(!is_dicom_part10(&mut cursor).unwrap());
}
