// Copyright (C) 2024 Philipp Hofer
//
// Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
// the European Commission - subsequent versions of the EUPL (the "Licence").
// You may not use this work except in compliance with the Licence.
//
// You should have received a copy of the European Union Public License along
// with this program.  If not, you may obtain a copy of the Licence at:
// <https://joinup.ec.europa.eu/software/page/eupl>
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Licence is distributed on an "AS IS" basis,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the Licence for the specific language governing permissions and
// limitations under the Licence.

use std::sync::Arc;

use clap::{command, Parser};
use risp::{
    config::Config,
    law::{responsible::always_true, Classifier, Law},
    misc::clear_cache,
};

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    /// Path to the config of a law text
    #[arg(short, long)]
    config: String,

    /// Parses a single paragraph (for debugging, e.g. https://www.ris.bka.gv.at/Dokumente/Bundesnormen/NOR40217849/NOR40217849.xml)
    /// Conflicts with `config` (either parse full law XOR single paragraph)
    #[arg(short, long)]
    par_url: Option<String>,

    /// Clears the cache (downloaded laws + paragraphs)
    #[arg(long)]
    clear_cache: bool,
}

fn main() {
    env_logger::init();

    let args = Args::parse();

    if args.clear_cache {
        if let Err(e) = clear_cache() {
            println!("Failed to clear cache: {e:?}");
        }
    }

    if let Some(par_url) = &args.par_url {
        let (_, mut builder, parser) = Config::load(&args.config).unwrap();
        builder.add_classifier(Classifier::new("always-true", Arc::new(always_true)));
        builder.new_header("initial");
        parser.parse(par_url, &mut builder).unwrap();
        let law: Law = builder.into();
        println!("{law:?}");
    } else {
        let law = Law::from_config(&args.config).unwrap();
        law.to_md();
    }
}
