//! Route handlers for repository pages.
//!
//! Covers two routes: the repository list (`/`) and the repository detail
//! page (`/{repo}`).  The detail handler opens the repository with `gix`,
//! collects branch and tag summaries via the service layer, reads the
//! description from `.git/description`, and renders the README as HTML.

use askama::Template;
use askama_web::WebTemplate;
use axum::extract::State;
use axum::response::IntoResponse;

use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd, html};

use crate::config::SiteConfig;
use crate::error::Result;
use crate::filters;
use crate::git::{self, commit_date};
use crate::routes::{AppState, RepoName};

/// Reads the repository description from `.git/description`, returning `None`
/// if the file is missing, empty, or contains the default git placeholder text.
fn repo_description(git_repo: &gix::Repository) -> Option<String> {
    std::fs::read_to_string(git_repo.path().join("description"))
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty() && !s.starts_with("Unnamed repository"))
}

/// Returns `true` if `url` is a relative path that should be rewritten to
/// point at the raw file serving route.
fn is_relative_url(url: &str) -> bool {
    !url.starts_with("http://")
        && !url.starts_with("https://")
        && !url.starts_with('#')
        && !url.starts_with("mailto:")
        && !url.starts_with("data:")
}

/// Template context for the repository detail page.
#[derive(Template, WebTemplate)]
#[template(path = "repo.html")]
struct Repo {
    name: String,
    description: Option<String>,
    branches: Vec<git::BranchInfo>,
    tags: Vec<git::TagInfo>,
    commit_count: usize,
    head_sha: Option<String>,
    default_branch: Option<String>,
    readme: Option<String>,
    site: std::sync::Arc<SiteConfig>,
}

/// Renders the detail page for a single repository, including its branches,
/// tags, and description.  Returns [`Error::RepoNotFound`] if no repository
/// exists at the given name, or [`Error::GitCorrupt`] if the ref database
/// cannot be read.
pub async fn detail(
    State(state): State<AppState>,
    RepoName(name): RepoName,
) -> Result<impl IntoResponse> {
    let git_repo = git::open_repo(&state.root, &name)?;

    let branches = git::load_branches(&git_repo);
    let tags = git::load_tags(&git_repo);
    let description = repo_description(&git_repo);
    let commit_count = git::commit_count(&git_repo);
    let head_id = git_repo.head_id().ok();

    let head_sha = head_id.map(|id| id.to_string());

    let base_url = state.site.base_url.clone();
    let site = state.site;

    let readme = ["HEAD:README.md", "HEAD:README", "HEAD:readme.md"]
        .iter()
        .find_map(|&spec| {
            let blob = git_repo
                .rev_parse_single(spec)
                .ok()
                .and_then(|id| id.object().ok())
                .and_then(|obj| obj.try_into_blob().ok())?;

            let text = std::str::from_utf8(&blob.data).ok()?;

            let mut rendered = String::new();
            let mut opts = Options::empty();
            opts.insert(Options::ENABLE_TABLES);
            opts.insert(Options::ENABLE_FOOTNOTES);
            opts.insert(Options::ENABLE_STRIKETHROUGH);
            opts.insert(Options::ENABLE_TASKLISTS);
            opts.insert(Options::ENABLE_SMART_PUNCTUATION);
            opts.insert(Options::ENABLE_HEADING_ATTRIBUTES);
            opts.insert(Options::ENABLE_GFM);
            opts.insert(Options::ENABLE_DEFINITION_LIST);
            opts.insert(Options::ENABLE_SUPERSCRIPT);
            opts.insert(Options::ENABLE_MATH);
            let events = Parser::new_ext(text, opts)
                .filter(|event| {
                    !matches!(event,
                        Event::Html(_)
                        | Event::InlineHtml(_)
                        | Event::Start(Tag::HtmlBlock)
                        | Event::End(TagEnd::HtmlBlock)
                    )
                })
                .map(|event| match event {
                Event::Start(Tag::Image {
                    link_type,
                    dest_url,
                    title,
                    id,
                }) => {
                    let dest_url = match &head_sha {
                        Some(sha) if is_relative_url(&dest_url) => format!(
                            "{}/{}/commits/{}/raw/{}",
                            base_url,
                            name,
                            sha,
                            dest_url
                        )
                        .into(),
                        _ => dest_url,
                    };
                    Event::Start(Tag::Image {
                        link_type,
                        dest_url,
                        title,
                        id,
                    })
                }
                Event::Start(Tag::Link {
                    link_type,
                    dest_url,
                    title,
                    id,
                }) => {
                    let dest_url = match &head_sha {
                        Some(sha) if is_relative_url(&dest_url) => format!(
                            "{}/{}/commits/{}/tree/{}",
                            base_url,
                            name,
                            sha,
                            dest_url
                        )
                        .into(),
                        _ => dest_url,
                    };
                    Event::Start(Tag::Link {
                        link_type,
                        dest_url,
                        title,
                        id,
                    })
                }
                _ => event,
            });
            html::push_html(&mut rendered, events);

            Some(rendered)
        });

    let default_branch = git_repo.head_name().ok().flatten().map(|h| h.shorten().to_string());

    Ok(Repo {
        name,
        description,
        branches,
        tags,
        commit_count,
        head_sha,
        default_branch,
        readme,
        site,
    })
}

/// Template context for a single repository in the list.
struct RepoSummary {
    name: String,
    description: Option<String>,
    commit_count: usize,
    last_commit: Option<String>,
}

/// Template context for the repository list page.
#[derive(Template, WebTemplate)]
#[template(path = "repo_list.html")]
struct RepoList {
    repos: Vec<RepoSummary>,
    site: std::sync::Arc<SiteConfig>,
}

/// Renders the repository list page by scanning the root directory for git
/// repositories.  Entries that cannot be opened as a git repository are
/// skipped.  The list is sorted by latest commit first.
pub async fn list(State(state): State<AppState>) -> Result<impl IntoResponse> {
    let mut repos: Vec<RepoSummary> = std::fs::read_dir(&state.root)?
        .filter_map(|entry| {
            let name = entry.ok()?.file_name().to_string_lossy().into_owned();
            let git_repo = git::open_repo(&state.root, &name).ok()?;
            let description = repo_description(&git_repo);

            let commit_count = git::commit_count(&git_repo);
            let head_id = git_repo.head_id().ok();

            let last_commit = head_id
                .and_then(|id| id.object().ok())
                .and_then(|obj| obj.try_into_commit().ok())
                .and_then(|commit| commit_date(&commit));

            Some(RepoSummary {
                name,
                description,
                commit_count,
                last_commit,
            })
        })
        .collect();

    repos.sort_by(|a, b| b.last_commit.cmp(&a.last_commit));

    Ok(RepoList { repos, site: state.site })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn relative_http() {
        assert!(!is_relative_url("http://example.com"));
    }

    #[test]
    fn relative_https() {
        assert!(!is_relative_url("https://example.com"));
    }

    #[test]
    fn relative_http_case_sensitive() {
        // Known quirk: uppercase scheme not matched, treated as relative
        assert!(is_relative_url("Http://example.com"));
    }

    #[test]
    fn relative_hash() {
        assert!(!is_relative_url("#section"));
    }

    #[test]
    fn relative_mailto() {
        assert!(!is_relative_url("mailto:user@host"));
    }

    #[test]
    fn relative_data() {
        assert!(!is_relative_url("data:text/plain,hi"));
    }

    #[test]
    fn relative_path_relative() {
        assert!(is_relative_url("relative/path"));
    }

    #[test]
    fn relative_path_absolute() {
        assert!(is_relative_url("/absolute/path"));
    }
}
