//! MCP resource providers

use anyhow::Result;
use kogral_core::{
    models::NodeType,
    storage::{filesystem::FilesystemStorage, Storage},
};
use tracing::info;

use crate::types::{Resource, ResourceContents};

/// List available resources
pub async fn list_resources() -> Result<Vec<Resource>> {
    Ok(vec![
        Resource {
            uri: "kogral://project/notes".to_string(),
            name: "Project Notes".to_string(),
            description: Some("All notes in the current project".to_string()),
            mime_type: Some("text/markdown".to_string()),
        },
        Resource {
            uri: "kogral://project/decisions".to_string(),
            name: "Project Decisions".to_string(),
            description: Some("All architectural decisions in the current project".to_string()),
            mime_type: Some("text/markdown".to_string()),
        },
        Resource {
            uri: "kogral://project/guidelines".to_string(),
            name: "Project Guidelines".to_string(),
            description: Some("All guidelines in the current project".to_string()),
            mime_type: Some("text/markdown".to_string()),
        },
        Resource {
            uri: "kogral://project/patterns".to_string(),
            name: "Project Patterns".to_string(),
            description: Some("All design patterns in the current project".to_string()),
            mime_type: Some("text/markdown".to_string()),
        },
        Resource {
            uri: "kogral://shared/guidelines".to_string(),
            name: "Shared Guidelines".to_string(),
            description: Some("Inherited base guidelines".to_string()),
            mime_type: Some("text/markdown".to_string()),
        },
        Resource {
            uri: "kogral://shared/patterns".to_string(),
            name: "Shared Patterns".to_string(),
            description: Some("Inherited base patterns".to_string()),
            mime_type: Some("text/markdown".to_string()),
        },
    ])
}

/// Read resource contents
pub async fn read_resource(uri: &str) -> Result<ResourceContents> {
    info!("Reading resource: {}", uri);

    let storage = FilesystemStorage::new(std::path::PathBuf::from(".kogral"));
    let graph = storage.load_graph("default").await?;

    let (scope, node_type) = parse_uri(uri)?;

    let nodes: Vec<_> = graph
        .nodes
        .values()
        .filter(|node| {
            let type_match = match node_type.as_str() {
                "notes" => node.node_type == NodeType::Note,
                "decisions" => node.node_type == NodeType::Decision,
                "guidelines" => node.node_type == NodeType::Guideline,
                "patterns" => node.node_type == NodeType::Pattern,
                _ => false,
            };

            let scope_match = match scope.as_str() {
                "project" => node.project.is_some(),
                "shared" => node.project.is_none(),
                _ => true,
            };

            type_match && scope_match
        })
        .collect();

    let mut content = format!("# {}\n\n", get_title_for_uri(uri));
    content.push_str(&format!("Found {} node(s)\n\n", nodes.len()));

    for node in nodes {
        content.push_str(&format!("## {}\n\n", node.title));
        content.push_str(&format!("**ID:** {}\n", node.id));
        content.push_str(&format!("**Type:** {:?}\n", node.node_type));
        content.push_str(&format!("**Status:** {:?}\n", node.status));
        content.push_str(&format!("**Created:** {}\n", node.created));

        if !node.tags.is_empty() {
            content.push_str(&format!("**Tags:** {}\n", node.tags.join(", ")));
        }

        content.push_str(&format!("\n{}\n\n---\n\n", node.content));
    }

    Ok(ResourceContents {
        uri: uri.to_string(),
        mime_type: "text/markdown".to_string(),
        text: content,
    })
}

fn parse_uri(uri: &str) -> Result<(String, String)> {
    if !uri.starts_with("kogral://") {
        return Err(anyhow::anyhow!("Invalid URI scheme, expected kogral://"));
    }

    let path = &uri[9..];
    let parts: Vec<&str> = path.split('/').collect();

    if parts.len() != 2 {
        return Err(anyhow::anyhow!(
            "Invalid URI format, expected kogral://<scope>/<type>"
        ));
    }

    Ok((parts[0].to_string(), parts[1].to_string()))
}

fn get_title_for_uri(uri: &str) -> String {
    match uri {
        "kogral://project/notes" => "Project Notes",
        "kogral://project/decisions" => "Project Architectural Decisions",
        "kogral://project/guidelines" => "Project Guidelines",
        "kogral://project/patterns" => "Project Design Patterns",
        "kogral://shared/guidelines" => "Shared Guidelines",
        "kogral://shared/patterns" => "Shared Design Patterns",
        _ => "KOGRAL Resource",
    }
    .to_string()
}
