//! VBI Data Descriptor — ETSI EN 300 468 §6.2.47 (tag 0x45).
//!
//! Table 106 (PDF p. 110). Carried in PMT ES_info for an elementary stream
//! carrying VBI data (per ETSI EN 301 775). Body is a loop of entries, each a
//! `data_service_id` byte + an 8-bit `data_service_descriptor_length` + that
//! many service-descriptor bytes.
//!
//! The first loop level (data_service_id + length-delimited service block) is
//! typed. For `data_service_id` values `0x01`–`0x02`, `0x04`–`0x07` (Table 106/107), each
//! service-descriptor byte encodes `reserved(2)|field_parity(1)|line_offset(5)`;
//! other values are kept as raw reserved bytes.

use super::descriptor_body;
use crate::error::{Error, Result};
use alloc::vec::Vec;
use dvb_common::{Parse, Serialize};

/// Descriptor tag for VBI_data_descriptor.
pub const TAG: u8 = 0x45;
const HEADER_LEN: usize = 2;
const ENTRY_HEADER_LEN: usize = 2;
const MAX_BODY_LEN: usize = u8::MAX as usize;
const MAX_SERVICE_LEN: usize = u8::MAX as usize;

/// Per-service-descriptor content, keyed by `data_service_id`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub enum VbiService<'a> {
    /// `data_service_id` 0x01–0x02, 0x04–0x07: each byte is
    /// `reserved_future_use(2)|field_parity(1)|line_offset(5)` (Table 106).
    Lines(Vec<VbiLine>),
    /// `data_service_id` 0x00, 0x03, or 0x08+: raw reserved bytes.
    Reserved(&'a [u8]),
}

/// One VBI line entry (Table 106 per-byte layout for ids 0x01–0x07).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct VbiLine {
    /// `field_parity` (1 bit) — `[5]` of the service-descriptor byte.
    pub field_parity: bool,
    /// `line_offset` (5 bits) — `[4:0]` of the service-descriptor byte.
    pub line_offset: u8,
}

/// One VBI data service entry.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct VbiDataEntry<'a> {
    /// data_service_id (EN 300 468 Table 107): 0x01 = EBU teletext,
    /// 0x02 = inverted teletext, 0x04 = VPS, 0x05 = WSS, 0x06 = closed
    /// captioning, 0x07 = monochrome 4:2:2 samples; others reserved/user.
    pub data_service_id: u8,
    /// Per-service content, typed for ids 0x01–0x02, 0x04–0x07.
    pub service_descriptor: VbiService<'a>,
}

/// VBI Data Descriptor.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct VbiDataDescriptor<'a> {
    /// Service entries in wire order.
    pub entries: Vec<VbiDataEntry<'a>>,
}

impl<'a> Parse<'a> for VbiDataDescriptor<'a> {
    type Error = crate::error::Error;
    fn parse(bytes: &'a [u8]) -> Result<Self> {
        let body = descriptor_body(
            bytes,
            TAG,
            "VbiDataDescriptor",
            "unexpected tag for VBI_data_descriptor",
        )?;
        let mut entries = Vec::new();
        let mut pos = 0;
        while pos < body.len() {
            if pos + ENTRY_HEADER_LEN > body.len() {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "truncated VBI data entry header",
                });
            }
            let data_service_id = body[pos];
            let svc_len = body[pos + 1] as usize;
            pos += ENTRY_HEADER_LEN;
            if pos + svc_len > body.len() {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "data_service_descriptor_length exceeds descriptor body",
                });
            }
            let svc_bytes = &body[pos..pos + svc_len];
            pos += svc_len;
            let service_descriptor = if matches!(data_service_id, 0x01 | 0x02 | 0x04..=0x07) {
                let lines = svc_bytes
                    .iter()
                    .map(|&b| VbiLine {
                        field_parity: (b & 0x20) != 0,
                        line_offset: b & 0x1F,
                    })
                    .collect();
                VbiService::Lines(lines)
            } else {
                VbiService::Reserved(svc_bytes)
            };
            entries.push(VbiDataEntry {
                data_service_id,
                service_descriptor,
            });
        }
        Ok(Self { entries })
    }
}

impl Serialize for VbiDataDescriptor<'_> {
    type Error = crate::error::Error;
    fn serialized_len(&self) -> usize {
        HEADER_LEN
            + self
                .entries
                .iter()
                .map(|e| {
                    ENTRY_HEADER_LEN
                        + match &e.service_descriptor {
                            VbiService::Lines(lines) => lines.len(),
                            VbiService::Reserved(b) => b.len(),
                        }
                })
                .sum::<usize>()
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        if buf.len() < len {
            return Err(Error::OutputBufferTooSmall {
                need: len,
                have: buf.len(),
            });
        }
        let body_len = len - HEADER_LEN;
        if body_len > MAX_BODY_LEN {
            return Err(Error::InvalidDescriptor {
                tag: TAG,
                reason: "VBI_data_descriptor body exceeds 255 bytes",
            });
        }
        buf[0] = TAG;
        buf[1] = body_len as u8;
        let mut pos = HEADER_LEN;
        for e in &self.entries {
            let svc_len = match &e.service_descriptor {
                VbiService::Lines(lines) => lines.len(),
                VbiService::Reserved(b) => b.len(),
            };
            if svc_len > MAX_SERVICE_LEN {
                return Err(Error::InvalidDescriptor {
                    tag: TAG,
                    reason: "service_descriptor exceeds 255 bytes (8-bit length field)",
                });
            }
            buf[pos] = e.data_service_id;
            buf[pos + 1] = svc_len as u8;
            pos += ENTRY_HEADER_LEN;
            match &e.service_descriptor {
                VbiService::Lines(lines) => {
                    for line in lines {
                        buf[pos] =
                            0xC0 | (u8::from(line.field_parity) << 5) | (line.line_offset & 0x1F);
                        pos += 1;
                    }
                }
                VbiService::Reserved(b) => {
                    buf[pos..pos + b.len()].copy_from_slice(b);
                    pos += b.len();
                }
            }
        }
        Ok(len)
    }
}
impl<'a> crate::traits::DescriptorDef<'a> for VbiDataDescriptor<'a> {
    const TAG: u8 = TAG;
    const NAME: &'static str = "VBI_DATA";
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_single_entry() {
        // data_service_id=0x01 (EBU teletext), 2 line bytes: 0xC1, 0xC2
        // 0xC1 = reserved(2)=11 | field_parity=0 | line_offset=00001 → fp=false, lo=1
        // 0xC2 = reserved(2)=11 | field_parity=0 | line_offset=00010 → fp=false, lo=2
        let bytes = [TAG, 4, 0x01, 0x02, 0xC1, 0xC2];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries.len(), 1);
        assert_eq!(d.entries[0].data_service_id, 0x01);
        match &d.entries[0].service_descriptor {
            VbiService::Lines(lines) => {
                assert_eq!(lines.len(), 2);
                assert!(!lines[0].field_parity);
                assert_eq!(lines[0].line_offset, 0x01);
                assert!(!lines[1].field_parity);
                assert_eq!(lines[1].line_offset, 0x02);
            }
            other => panic!("expected Lines, got {other:?}"),
        }
    }

    #[test]
    fn parse_multiple_entries() {
        // 0xAA = 10_1_01010 → fp=true, lo=0x0A=10
        // 0xBB = 10_1_11011 → fp=true, lo=0x1B=27
        // 0xCC = 11_0_01100 → fp=false, lo=0x0C=12
        let bytes = [TAG, 7, 0x04, 0x01, 0xAA, 0x05, 0x02, 0xBB, 0xCC];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries.len(), 2);
        assert_eq!(d.entries[0].data_service_id, 0x04);
        match &d.entries[0].service_descriptor {
            VbiService::Lines(lines) => {
                assert_eq!(lines.len(), 1);
                assert!(lines[0].field_parity);
                assert_eq!(lines[0].line_offset, 0x0A);
            }
            other => panic!("expected Lines, got {other:?}"),
        }
        assert_eq!(d.entries[1].data_service_id, 0x05);
        match &d.entries[1].service_descriptor {
            VbiService::Lines(lines) => {
                assert_eq!(lines.len(), 2);
                assert!(lines[0].field_parity);
                assert_eq!(lines[0].line_offset, 0x1B);
                assert!(!lines[1].field_parity);
                assert_eq!(lines[1].line_offset, 0x0C);
            }
            other => panic!("expected Lines, got {other:?}"),
        }
    }

    #[test]
    fn parse_entry_with_empty_service_block() {
        let bytes = [TAG, 2, 0x06, 0x00];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries.len(), 1);
        match &d.entries[0].service_descriptor {
            VbiService::Lines(lines) => assert!(lines.is_empty()),
            other => panic!("expected Lines, got {other:?}"),
        }
    }

    #[test]
    fn parse_reserved_data_service_id() {
        let bytes = [TAG, 4, 0x00, 0x02, 0xDE, 0xAD];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries.len(), 1);
        assert_eq!(d.entries[0].data_service_id, 0x00);
        match &d.entries[0].service_descriptor {
            VbiService::Reserved(b) => assert_eq!(*b, &[0xDE, 0xAD]),
            other => panic!("expected Reserved, got {other:?}"),
        }
    }

    #[test]
    fn parse_rejects_wrong_tag() {
        assert!(matches!(
            VbiDataDescriptor::parse(&[0x46, 0]).unwrap_err(),
            Error::InvalidDescriptor { tag: 0x46, .. }
        ));
    }

    #[test]
    fn parse_rejects_short_buffer() {
        // declares 4 body bytes, only 2 present
        let bytes = [TAG, 4, 0x01, 0x02];
        assert!(matches!(
            VbiDataDescriptor::parse(&bytes).unwrap_err(),
            Error::BufferTooShort { .. }
        ));
    }

    #[test]
    fn parse_rejects_inner_length_overrun() {
        // entry declares 5 service bytes but only 1 remains in body
        let bytes = [TAG, 3, 0x01, 0x05, 0xAA];
        assert!(matches!(
            VbiDataDescriptor::parse(&bytes).unwrap_err(),
            Error::InvalidDescriptor { tag: TAG, .. }
        ));
    }

    #[test]
    fn empty_descriptor_valid() {
        let d = VbiDataDescriptor::parse(&[TAG, 0]).unwrap();
        assert!(d.entries.is_empty());
    }

    #[test]
    fn serialize_round_trip() {
        let d = VbiDataDescriptor {
            entries: vec![
                VbiDataEntry {
                    data_service_id: 0x01,
                    service_descriptor: VbiService::Lines(vec![
                        VbiLine {
                            field_parity: false,
                            line_offset: 0x01,
                        },
                        VbiLine {
                            field_parity: false,
                            line_offset: 0x02,
                        },
                        VbiLine {
                            field_parity: false,
                            line_offset: 0x03,
                        },
                    ]),
                },
                VbiDataEntry {
                    data_service_id: 0x04,
                    service_descriptor: VbiService::Lines(vec![]),
                },
            ],
        };
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(VbiDataDescriptor::parse(&buf).unwrap(), d);
    }

    #[test]
    fn serialize_round_trip_reserved() {
        let d = VbiDataDescriptor {
            entries: vec![VbiDataEntry {
                data_service_id: 0x80,
                service_descriptor: VbiService::Reserved(&[0xDE, 0xAD]),
            }],
        };
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(VbiDataDescriptor::parse(&buf).unwrap(), d);
    }

    #[test]
    fn byte_identity_with_reserved_bits() {
        let bytes = [TAG, 4, 0x01, 0x02, 0xC1, 0xC2];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        let mut buf = vec![0u8; d.serialized_len()];
        d.serialize_into(&mut buf).unwrap();
        assert_eq!(buf, bytes);
    }

    #[test]
    fn data_service_id_0x03_is_reserved() {
        let bytes = [TAG, 3, 0x03, 0x01, 0xAA];
        let d = VbiDataDescriptor::parse(&bytes).unwrap();
        assert_eq!(d.entries[0].data_service_id, 0x03);
        match &d.entries[0].service_descriptor {
            VbiService::Reserved(b) => assert_eq!(*b, &[0xAA]),
            other => panic!("expected Reserved for id 0x03, got {other:?}"),
        }
    }

    #[test]
    fn serialize_rejects_small_buffer() {
        let d = VbiDataDescriptor {
            entries: vec![VbiDataEntry {
                data_service_id: 0x01,
                service_descriptor: VbiService::Lines(vec![VbiLine {
                    field_parity: false,
                    line_offset: 0x0A,
                }]),
            }],
        };
        let mut tiny = [0u8; 3];
        assert!(matches!(
            d.serialize_into(&mut tiny).unwrap_err(),
            Error::OutputBufferTooSmall { .. }
        ));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_serialize_stable() {
        // Borrowed-byte fields cannot deserialize from a JSON array (serde_json
        // requires a borrowed-str for &[u8]); assert the Serialize half is
        // stable, matching the other borrowed descriptors (e.g.
        // content_identifier) in this crate.
        let make = || VbiDataDescriptor {
            entries: vec![VbiDataEntry {
                data_service_id: 0x01,
                service_descriptor: VbiService::Lines(vec![
                    VbiLine {
                        field_parity: false,
                        line_offset: 0x01,
                    },
                    VbiLine {
                        field_parity: false,
                        line_offset: 0x02,
                    },
                ]),
            }],
        };
        let json = serde_json::to_string(&make()).unwrap();
        assert!(json.contains("data_service_id"));
        assert_eq!(json, serde_json::to_string(&make()).unwrap());
    }
}
