//! `ckg routes` — HTTP routes extracted from frameworks (Axum, FastAPI, Flask).
//!
//! Routes are stored as `Symbol{kind: "route", qname: "<METHOD> <path>",
//! doc: "handler=<name>"}` rows. `--method` filters by HTTP verb.
use std::path::PathBuf;

use anyhow::Result;
use clap::Args as ClapArgs;
use cozo::DataValue;

#[derive(ClapArgs, Debug)]
pub struct Args {
    /// Filter by HTTP method (GET, POST, ...).
    #[arg(long)]
    pub method: Option<String>,
}

pub fn run(home: Option<PathBuf>, args: Args) -> Result<()> {
    let (_base, storage) = super::repo_lookup::open_for(home, None)?;
    let rows = storage.run_immutable(
        "?[qname, file, line, doc] := *Symbol{qname, kind, file, line, doc}, kind = \"route\"",
    )?;
    if rows.rows.is_empty() {
        println!("(no routes detected — Axum / FastAPI / Flask supported)");
        return Ok(());
    }
    let filter = args.method.as_deref().map(str::to_uppercase);
    let mut shown = 0;
    for row in &rows.rows {
        let qname = match &row[0] {
            DataValue::Str(s) => s.to_string(),
            _ => continue,
        };
        if let Some(f) = &filter
            && !qname.starts_with(f)
        {
            continue;
        }
        let file = match &row[1] {
            DataValue::Str(s) => s.to_string(),
            v => format!("{v:?}"),
        };
        let line = match &row[2] {
            DataValue::Num(n) => format!("{n:?}"),
            v => format!("{v:?}"),
        };
        let doc = match &row[3] {
            DataValue::Str(s) => s.to_string(),
            v => format!("{v:?}"),
        };
        println!("  {qname:<40}  {doc:<30}  {file}:{line}");
        shown += 1;
    }
    println!("\n{shown} route(s)");
    Ok(())
}
