use eyre::Result;
use log::warn;

use dkl::bootstrap::UdevFilter;

pub struct Device {
    sysname: String,
    output: String,
}

impl Device {
    pub fn sysname(&self) -> &str {
        self.sysname.as_str()
    }

    pub fn properties(&self) -> impl Iterator<Item = (&str, &str)> {
        self.output
            .lines()
            .filter_map(|line| line.strip_prefix("E: ")?.split_once('='))
    }
}

pub fn get_devices(class: &str) -> Result<Vec<Device>> {
    let mut devices = Vec::new();

    // none of libudev and udev crates were able to list network devices.
    // falling back to manual sysfs scanning :(
    //
    // Even when given a syspath,
    // - udev crate failed to see all properties;
    // - libudev crate segfaulted on the second property (SYSNUM ok, then segfault).
    // falling back to parsing udevadm output :(
    //
    // The best fix would be to check what's wrong with udev crate.

    let entries = std::fs::read_dir(format!("/sys/class/{class}"))?;
    for entry in entries {
        let Ok(entry) = entry else {
            continue;
        };

        let path = entry.path();
        let path = path.to_string_lossy();

        let output = std::process::Command::new("udevadm")
            .args(["info", &format!("--path={path}")])
            .stderr(std::process::Stdio::piped())
            .output()?;

        if !output.status.success() {
            warn!("udevadm failed for {path}: {}", output.status);
            continue;
        }

        let output = String::from_utf8_lossy(&output.stdout);

        let name = entry.file_name();
        let dev = Device {
            sysname: name.to_string_lossy().to_string(),
            output: output.into_owned(),
        };

        devices.push(dev);
    }

    Ok(devices)
}

pub async fn all() -> Result<Devs> {
    let output = tokio::process::Command::new("udevadm")
        .args(["info", "-e"])
        .stderr(std::process::Stdio::inherit())
        .output()
        .await?;

    if !output.status.success() {
        return Err(eyre::format_err!("udevadm failed: {}", output.status));
    }

    Ok(Devs {
        data: unsafe { String::from_utf8_unchecked(output.stdout) },
    })
}

pub async fn by_path(path: &str) -> Result<Devs> {
    let output = tokio::process::Command::new("udevadm")
        .args(["info", path])
        .stderr(std::process::Stdio::inherit())
        .output()
        .await?;

    if !output.status.success() {
        return Err(eyre::format_err!("udevadm failed: {}", output.status));
    }

    Ok(Devs {
        data: unsafe { String::from_utf8_unchecked(output.stdout) },
    })
}

pub struct Devs {
    data: String,
}

impl<'t> Devs {
    pub fn iter(&'t self) -> impl Iterator<Item = Dev<'t>> {
        self.data.split("\n\n").filter(|s| !s.is_empty()).map(Dev)
    }

    pub fn of_subsystem(&'t self, subsystem: &str) -> impl Iterator<Item = Dev<'t>> {
        self.iter().filter(|dev| dev.subsystem() == Some(subsystem))
    }
}

pub struct Dev<'t>(&'t str);

impl<'t> Dev<'t> {
    pub fn raw(&self) -> &str {
        self.0
    }

    // alpine's udev prefixes we've seen:
    // - P: Device path in /sys/
    // - N: Kernel device node name
    // - S: Device node symlink
    // - L: Device node symlink priority [ignored]
    // - E: Device property

    fn by_prefix(&self, prefix: &'static str) -> impl Iterator<Item = &str> {
        self.0.lines().filter_map(move |l| l.strip_prefix(prefix))
    }

    /// Device path in /sys/
    pub fn path(&self) -> Option<&str> {
        self.by_prefix("P: ").next()
    }

    /// Kernel device node name
    pub fn name(&self) -> Option<&str> {
        self.by_prefix("N: ").next()
    }

    /// Device node symlinks
    pub fn symlinks(&self) -> Vec<&str> {
        self.by_prefix("S: ").collect()
    }

    /// Device properties
    pub fn properties(&self) -> impl Iterator<Item = (&str, &str)> {
        self.by_prefix("E: ").filter_map(|s| s.split_once("="))
    }

    /// Device property
    pub fn property(&self, name: &str) -> Option<&str> {
        self.properties()
            .filter_map(|(n, v)| (n == name).then_some(v))
            .next()
    }

    /// Device subsystem
    pub fn subsystem(&self) -> Option<&str> {
        self.property("SUBSYSTEM")
    }
}

pub enum Filter {
    Has(String),
    Eq(String, String),
    Glob(String, glob::Pattern),
    And(Vec<Filter>),
    Or(Vec<Filter>),
    Not(Box<Filter>),
    False,
}

impl Filter {
    pub fn matches(&self, dev: &Dev) -> bool {
        match self {
            Self::False => false,
            Self::Has(k) => dev.property(k).is_some(),
            Self::Eq(k, v) => dev.properties().any(|kv| kv == (k, v)),
            Self::Glob(k, pattern) => dev
                .properties()
                .any(|(pk, pv)| pk == k && pattern.matches(pv)),
            Self::And(ops) => ops.iter().all(|op| op.matches(dev)),
            Self::Or(ops) => ops.iter().any(|op| op.matches(dev)),
            Self::Not(op) => !op.matches(dev),
        }
    }
}

impl From<UdevFilter> for Filter {
    fn from(filter: UdevFilter) -> Filter {
        use UdevFilter::*;
        match filter {
            Has(p) => Filter::Has(p),
            Eq(p, v) => Filter::Eq(p, v),
            Glob(p, pattern) => match glob::Pattern::new(&pattern) {
                Ok(pattern) => Filter::Glob(p, pattern),
                Err(e) => {
                    warn!("pattern {pattern:?} will never match: {e}");
                    Filter::False
                }
            },
            And(ops) => Filter::And(ops.into_iter().map(|op| op.into()).collect()),
            Or(ops) => Filter::Or(ops.into_iter().map(|op| op.into()).collect()),
            Not(op) => Filter::Not(Box::new((*op).into())),
        }
    }
}
