//
// Copyright 2025 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use std::{fs, path::PathBuf};

use clap::Parser;
use oak_proto_rust::oak::packages::PackageList;
use prost::Message;

#[derive(Parser, Debug)]
#[group(skip)]
pub struct Params {
    /// Path to the published package list to inspect.
    #[arg(long, value_parser = path_is_file)]
    pub file_path: PathBuf,
}

fn path_is_file(s: &str) -> Result<PathBuf, String> {
    let path = PathBuf::from(s);
    if !fs::metadata(s).map_err(|err| err.to_string())?.is_file() {
        Err(String::from("path does not represent a file"))
    } else {
        Ok(path)
    }
}

fn main() {
    let Params { file_path } = Params::parse();
    let serialized_packages = fs::read(file_path).expect("could not read package list");
    let packages =
        PackageList::decode(serialized_packages.as_slice()).expect("could not package list");

    for package in packages.packages {
        println!("Published versions for package '{}':", package.name);
        for version_id in package.version_ids {
            println!("{version_id}");
        }
    }
}
