//! GitHub CLI dispatch. All flag-policy data and the sub × action
//! allowlists live in `commands/forges/gh.toml`. The handler is the
//! sub × action matrix routing logic plus a sub-handler for `gh api`
//! whose REST-vs-GraphQL routing, explicit-GET-for-fields rule, header
//! allowlist, and GraphQL mutation veto can't move to TOML.
use crate::parse::{Token, WordSet};
use crate::registry;
use crate::verdict::{SafetyLevel, Verdict};

// The api sub's flag surface. These lists stay in Rust as a known
// exception to the data-in-TOML principle: the field flags' semantics
// (require explicit `-X GET` on REST; veto mutation queries on
// GraphQL; pair as KEY=VALUE) are coupled to the validation logic
// just above. Adding a TOML primitive for "valued flag with KEY=VALUE
// content rules" is a future schema refinement.
static API_STANDALONE: WordSet = WordSet::new(&[
    "--include", "--paginate", "--silent", "--slurp", "--verbose",
    "-i",
]);

static API_VALUED: WordSet = WordSet::new(&[
    "--cache", "--hostname", "--jq", "--json", "--preview", "--template",
    "-p", "-q", "-t",
]);

static API_FIELD_FLAGS: WordSet = WordSet::new(&[
    "--field", "--raw-field",
    "-F", "-f",
]);

fn is_safe_api_header(value: &str) -> bool {
    let Some((name, _)) = value.split_once(':') else {
        return false;
    };
    let trimmed = name.trim();
    trimmed.eq_ignore_ascii_case("Accept")
        || trimmed.eq_ignore_ascii_case("X-GitHub-Api-Version")
}

pub fn is_safe_gh(tokens: &[Token]) -> Verdict {
    if tokens.len() < 2 {
        return Verdict::Denied;
    }
    if let Some(v @ Verdict::Allowed(_)) = registry::try_fallback_grammar("gh", tokens) {
        return v;
    }
    // Universal `gh <sub> --help` at length 3. The only piece of pure
    // handler logic — every sub forwards `--help` to its own help text,
    // which we don't model per-sub.
    if tokens.len() == 3 && matches!(tokens[2].as_str(), "--help" | "-h") {
        return Verdict::Allowed(SafetyLevel::Inert);
    }
    if let Some(v) = registry::try_sub_dispatch("gh", tokens) {
        return v;
    }
    registry::try_matrix_dispatch("gh", tokens).unwrap_or(Verdict::Denied)
}

/// Sub-handler for `gh api ...` / `glab api ...`. Called with tokens
/// in sub-dispatch convention: `tokens[0] = "api"`, `tokens[1] =
/// endpoint`, `tokens[2..] = args`. glab dispatches with
/// `super::gh::is_safe_gh_api(&tokens[1..])`.
pub fn is_safe_gh_api(tokens: &[Token]) -> Verdict {
    let endpoint = tokens.get(1).map(|t| t.as_str()).unwrap_or("");
    if endpoint == "graphql" {
        return is_safe_gh_api_graphql(tokens);
    }
    is_safe_gh_api_rest(tokens)
}

fn is_graphql_mutation(query: &str) -> bool {
    let mut s = query.trim_start();
    while s.starts_with('#') {
        s = match s.find('\n') {
            Some(pos) => s[pos + 1..].trim_start(),
            None => return false,
        };
    }
    s.starts_with("mutation")
        && s.as_bytes()
            .get(8)
            .is_none_or(|&b| b == b' ' || b == b'\t' || b == b'\n' || b == b'{' || b == b'(')
}

fn extract_field_value(tokens: &[Token], i: usize) -> Option<(&str, &str)> {
    let token = &tokens[i];
    let s = token.as_str();
    if let Some(rest) = s.strip_prefix("--field=")
        .or_else(|| s.strip_prefix("--raw-field="))
    {
        return rest.split_once('=');
    }
    if let Some(rest) = s.strip_prefix("-f").or_else(|| s.strip_prefix("-F"))
        && let Some(pair) = rest.split_once('=')
    {
        return Some(pair);
    }
    if API_FIELD_FLAGS.contains(token)
        && let Some(next) = tokens.get(i + 1)
    {
        return next.as_str().split_once('=');
    }
    None
}

fn is_safe_gh_api_graphql(tokens: &[Token]) -> Verdict {
    // tokens[0] = "api", tokens[1] = "graphql", args start at i=2.
    let mut i = 2;
    while i < tokens.len() {
        let token = &tokens[i];

        if token == "-X" || token == "--method" {
            i += 2;
            continue;
        }
        if token.starts_with("-X") || token.starts_with("--method=") {
            i += 1;
            continue;
        }

        if token == "-H" || token == "--header" {
            match tokens.get(i + 1) {
                Some(val) if is_safe_api_header(val.as_str()) => { i += 2; continue; }
                _ => return Verdict::Denied,
            }
        }
        if let Some(rest) = token.as_str().strip_prefix("-H=").or_else(|| token.as_str().strip_prefix("--header=")) {
            if is_safe_api_header(rest) { i += 1; continue; }
            return Verdict::Denied;
        }

        if token.starts_with('-') {
            if API_STANDALONE.contains(token) { i += 1; continue; }
            if API_VALUED.contains(token) { i += 2; continue; }
            if API_FIELD_FLAGS.contains(token) {
                if matches!(extract_field_value(tokens, i), Some(("query", val)) if is_graphql_mutation(val)) {
                    return Verdict::Denied;
                }
                i += 2;
                continue;
            }
            if let Some((_flag, _val)) = token.split_once('=') {
                let flag_part = Token::from_raw(_flag.to_string());
                if API_VALUED.contains(&flag_part) { i += 1; continue; }
                if API_FIELD_FLAGS.contains(&flag_part) {
                    if matches!(extract_field_value(tokens, i), Some(("query", val)) if is_graphql_mutation(val)) {
                        return Verdict::Denied;
                    }
                    i += 1;
                    continue;
                }
            }
            return Verdict::Denied;
        }

        i += 1;
    }
    Verdict::Allowed(SafetyLevel::Inert)
}

fn is_safe_gh_api_rest(tokens: &[Token]) -> Verdict {
    // tokens[0] = "api", tokens[1] = endpoint, tokens[2..] = args.
    // Start at i=1 so the endpoint walks past as a positional (no-op
    // in every flag branch), matching the original `is_safe_gh_api_rest`
    // semantics under the full-tokens convention.
    let mut i = 1;
    let mut has_fields = false;
    let mut has_explicit_get = false;
    while i < tokens.len() {
        let token = &tokens[i];

        if token == "-X" || token == "--method" {
            if tokens.get(i + 1).is_some_and(|m| m.eq_ignore_ascii_case("GET")) {
                has_explicit_get = true;
                i += 2;
                continue;
            }
            return Verdict::Denied;
        }
        if token.starts_with("-X") && token.len() > 2 && !token.starts_with("-X=") {
            if token.get(2..).is_some_and(|s| s.eq_ignore_ascii_case("GET")) {
                has_explicit_get = true;
                i += 1;
                continue;
            }
            return Verdict::Denied;
        }
        if token.starts_with("-X=") || token.starts_with("--method=") {
            let val = token.split_value("=").unwrap_or("");
            if val.eq_ignore_ascii_case("GET") {
                has_explicit_get = true;
                i += 1;
                continue;
            }
            return Verdict::Denied;
        }

        if token == "-H" || token == "--header" {
            match tokens.get(i + 1) {
                Some(val) if is_safe_api_header(val.as_str()) => { i += 2; continue; }
                _ => return Verdict::Denied,
            }
        }
        if let Some(rest) = token.as_str().strip_prefix("-H=").or_else(|| token.as_str().strip_prefix("--header=")) {
            if is_safe_api_header(rest) { i += 1; continue; }
            return Verdict::Denied;
        }

        if token.starts_with('-') {
            if API_STANDALONE.contains(token) { i += 1; continue; }
            if API_VALUED.contains(token) { i += 2; continue; }
            if API_FIELD_FLAGS.contains(token) {
                has_fields = true;
                i += 2;
                continue;
            }
            if let Some((_flag, _val)) = token.split_once('=') {
                let flag_part = Token::from_raw(_flag.to_string());
                if API_VALUED.contains(&flag_part) { i += 1; continue; }
                if API_FIELD_FLAGS.contains(&flag_part) {
                    has_fields = true;
                    i += 1;
                    continue;
                }
            }
            return Verdict::Denied;
        }

        i += 1;
    }
    if has_fields && !has_explicit_get {
        return Verdict::Denied;
    }
    Verdict::Allowed(SafetyLevel::Inert)
}

pub(in crate::handlers::forges) fn dispatch(_cmd: &str, _tokens: &[Token]) -> Option<Verdict> {
    // `gh` is dispatched through the TOML registry now (handler = "gh"
    // in commands/forges/gh.toml). Same for `glab` via its own handler.
    None
}

pub fn command_docs() -> Vec<crate::docs::CommandDoc> {
    // gh's docs come from the TOML registry's auto-render.
    Vec::new()
}

#[cfg(test)]
pub(super) const REGISTRY: &[crate::handlers::CommandEntry] = &[
    crate::handlers::CommandEntry::Paths { cmd: "gh", bare_ok: false, paths: &[
        "gh alias list",
        "gh attestation verify artifact",
        "gh auth status",
        "gh browse --no-browser",
        "gh cache list",
        "gh codespace list",
        "gh config list",
        "gh extension list",
        "gh gist list",
        "gh gist view 123",
        "gh gpg-key list",
        "gh issue list",
        "gh issue view 456",
        "gh label list",
        "gh org list",
        "gh pr list",
        "gh pr view 123",
        "gh pr diff 123",
        "gh pr checks 123",
        "gh pr status 123",
        "gh project list",
        "gh project view 1",
        "gh release list",
        "gh release view v1.0",
        "gh release download v1.0 --output -",
        "gh repo list",
        "gh repo view owner/repo",
        "gh ruleset list",
        "gh ruleset view 1",
        "gh run list",
        "gh run view 789",
        "gh run watch 123",
        "gh run rerun 12345",
        "gh search issues foo",
        "gh secret list",
        "gh ssh-key list",
        "gh status",
        "gh variable list",
        "gh workflow list",
        "gh workflow view ci",
        "gh api repos/o/r",
    ]},
];

#[cfg(test)]
mod tests {
    use crate::is_safe_command;

    fn check(cmd: &str) -> bool {
        is_safe_command(cmd)
    }

    safe! {
        pr_view: "gh pr view 123",
        pr_view_json: "gh pr view 123 --json title,body",
        pr_view_web: "gh pr view 123 --web",
        pr_view_comments: "gh pr view 123 --comments",
        pr_list: "gh pr list",
        pr_list_state: "gh pr list --state open",
        pr_list_label: "gh pr list --label bug",
        pr_list_author: "gh pr list --author user",
        pr_list_json: "gh pr list --json number,title --jq '.[].title'",
        pr_list_limit: "gh pr list --limit 50",
        pr_list_search: "gh pr list --search 'is:draft'",
        pr_diff: "gh pr diff 123",
        pr_diff_color: "gh pr diff 123 --color always",
        pr_diff_name_only: "gh pr diff 123 --name-only",
        pr_checks: "gh pr checks 123",
        pr_checks_watch: "gh pr checks 123 --watch",
        pr_checks_required: "gh pr checks 123 --required",
        issue_view: "gh issue view 456",
        issue_list: "gh issue list",
        issue_list_state: "gh issue list --state closed",
        auth_status: "gh auth status",
        search_issues: "gh search issues foo",
        search_issues_state: "gh search issues foo --state open",
        search_issues_json: "gh search issues foo --json number,title",
        search_prs: "gh search prs bar",
        search_repos: "gh search repos baz --language rust",
        run_view: "gh run view 789",
        run_view_log: "gh run view 789 --log",
        run_view_log_failed: "gh run view 789 --log-failed",
        run_view_exit_status: "gh run view 789 --exit-status",
        run_view_json: "gh run view 789 --json conclusion",
        run_view_json_jq: "gh run view 789 --json status,conclusion -q '.status'",
        run_view_json_jq_repo: "gh run view 789 --repo owner/repo --json status,conclusion -q '.status'",
        pr_list_jq_short: "gh pr list --json number -q '.[].number'",
        issue_list_jq_short: "gh issue list -q '.[] | .title' --json title",
        pr_help: "gh pr --help",
        issue_help: "gh issue --help",
        run_help: "gh run --help",
        search_help: "gh search --help",
        auth_help: "gh auth --help",
        browse_help: "gh browse --help",
        api_help: "gh api --help",
        release_help: "gh release --help",
        run_watch: "gh run watch 123",
        run_watch_repo: "gh run watch 123 --repo owner/repo",
        run_watch_exit: "gh run watch 123 --exit-status",
        run_rerun: "gh run rerun 12345",
        run_rerun_failed: "gh run rerun 12345 --failed",
        run_rerun_debug: "gh run rerun 12345 --debug",
        run_rerun_job: "gh run rerun 12345 --job job-id",
        run_rerun_repo: "gh run rerun 12345 --repo owner/repo",
        run_list: "gh run list",
        run_list_workflow: "gh run list --workflow ci.yml",
        run_list_branch: "gh run list --branch main",
        run_list_status: "gh run list --status completed",
        release_list: "gh release list",
        release_list_limit: "gh release list --limit 10",
        release_view: "gh release view v1.0",
        release_view_web: "gh release view v1.0 --web",
        release_download_stdout: "gh release download v1.0 --output -",
        release_download_pattern: "gh release download v1.0 --repo o/r --pattern 'SHA256SUMS.txt' --output -",
        release_download_short: "gh release download v1.0 -O - -p '*.tar.gz'",
        release_download_archive: "gh release download v1.0 --archive tar.gz --output out.tar.gz",
        release_download_dir: "gh release download v1.0 --output /tmp/out --dir /tmp",
        label_list: "gh label list",
        codespace_list: "gh codespace list",
        variable_list: "gh variable list",
        extension_list: "gh extension list",
        cache_list: "gh cache list",
        attestation_verify: "gh attestation verify artifact.tar.gz",
        gpg_key_list: "gh gpg-key list",
        ssh_key_list: "gh ssh-key list",
        status_safe: "gh status",
        browse_no_browser: "gh browse --no-browser",
        browse_no_browser_with_path: "gh browse src/main.rs --no-browser",
        api_get_implicit: "gh api repos/o/r/pulls/1",
        api_jq: "gh api repos/o/r/contents/f --jq '.content'",
        api_explicit_get: "gh api repos/o/r/pulls -X GET",
        api_paginate: "gh api repos/o/r/pulls --paginate",
        api_paginate_slurp: "gh api repos/o/r/pulls --paginate --slurp",
        api_paginate_jq: "gh api repos/o/r/pulls --paginate --jq '.[].title'",
        api_xget_short: "gh api repos/o/r/pulls -XGET",
        api_include: "gh api repos/o/r/pulls -i",
        api_silent: "gh api repos/o/r/pulls --silent",
        api_verbose: "gh api repos/o/r/pulls --verbose",
        api_cache: "gh api repos/o/r/pulls --cache 3600s",
        api_hostname: "gh api repos/o/r/pulls --hostname github.example.com",
        api_template: "gh api repos/o/r/pulls -t '{{.title}}'",
        api_preview: "gh api repos/o/r/pulls -p corsair",
        api_method_eq_get: "gh api repos/o/r/pulls --method=GET",
        api_combined: "gh api repos/o/r/pulls --paginate --slurp --jq '.[].title' --cache 60s",
        api_header_accept_raw: "gh api repos/o/r/contents/f?ref=branch -H 'Accept: application/vnd.github.raw'",
        api_header_accept_json: "gh api repos/o/r/contents/f -H 'Accept: application/vnd.github.v3+json'",
        api_header_api_version: "gh api repos/o/r/pulls -H 'X-GitHub-Api-Version: 2022-11-28'",
        api_header_long_form: "gh api repos/o/r/contents/f --header 'Accept: application/vnd.github.raw'",
        api_header_multiple: "gh api repos/o/r/contents/f -H 'Accept: application/vnd.github.raw' -H 'X-GitHub-Api-Version: 2022-11-28'",
        api_header_with_jq: "gh api repos/o/r/contents/f -H 'Accept: application/vnd.github.raw' --jq '.content'",
        gh_version: "gh --version",
        gist_list: "gh gist list",
        gist_view: "gh gist view abc123",
        org_list: "gh org list",
        project_list: "gh project list",
        project_view: "gh project view 1",
        ruleset_list: "gh ruleset list",
        ruleset_view: "gh ruleset view 1",
        config_list: "gh config list",
        alias_list: "gh alias list",
        secret_list: "gh secret list",
        issue_list_mention: "gh issue list --mention user",
        label_list_search: "gh label list --search bug",
        label_list_sort: "gh label list --sort name --order asc",
        cache_list_key: "gh cache list --key prefix",
        repo_list_language: "gh repo list --language rust",
        repo_list_archived: "gh repo list --archived",
        repo_view_branch: "gh repo view owner/repo --branch dev",
        workflow_list_all: "gh workflow list --all",
        workflow_view_yaml: "gh workflow view ci --yaml",
        workflow_view_ref: "gh workflow view ci --ref main",
        codespace_list_repo: "gh codespace list --repo owner/repo",
        variable_list_env: "gh variable list --env production",
        variable_list_org: "gh variable list --org myorg",
        api_field_with_get: "gh api repos/o/r/contents/f -X GET -f ref=abc --jq '.content'",
        api_field_with_get_eq: "gh api repos/o/r/contents/f --method=GET -f ref=abc",
        api_raw_field_with_get: "gh api repos/o/r/contents/f -X GET -F ref=abc",
        api_graphql_query: "gh api graphql -f query='{viewer{login}}' --jq '.data.viewer.login'",
        api_graphql_field: "gh api graphql --field query='{repository(owner:\"o\",name:\"r\"){name}}'",
        api_graphql_jq: "gh api graphql -f query='{viewer{login}}' -q '.data'",
        api_graphql_named_query: "gh api graphql -f query='query GetViewer{viewer{login}}'",
        api_graphql_with_vars: "gh api graphql -f query='{repository(owner:\"o\",name:\"r\"){name}}' -F owner=o",
        api_graphql_paginate: "gh api graphql --paginate -f query='{viewer{repositories(first:100){nodes{name}}}}'",
    }

    denied! {
        run_rerun_bare_denied: "gh run rerun",
        run_rerun_unknown_flag_denied: "gh run rerun 12345 --unknown",
        browse_without_flag_denied: "gh browse",
        issue_download_denied: "gh issue download",
        release_download_no_output_denied: "gh release download v1.0",
        release_download_pattern_no_output_denied: "gh release download v1.0 --pattern '*.tar.gz'",
        api_patch_denied: "gh api repos/o/r/pulls/1 -X PATCH -f body=x",
        api_post_denied: "gh api repos/o/r/pulls/1 -X POST",
        api_field_no_get_denied: "gh api repos/o/r/issues -f title=x",
        api_raw_field_no_get_denied: "gh api repos/o/r/issues --raw-field body=x",
        api_big_field_no_get_denied: "gh api repos/o/r/issues -F title=x",
        api_field_with_post_denied: "gh api repos/o/r/issues -X POST -f title=x",
        api_field_with_patch_denied: "gh api repos/o/r/issues -X PATCH -f title=x",
        api_graphql_mutation_denied: "gh api graphql -f query=mutation",
        api_graphql_mutation_brace_denied: "gh api graphql -f query='mutation{addStar}'",
        api_graphql_mutation_named_denied: "gh api graphql -f query='mutation AddStar{addStar}'",
        api_graphql_mutation_whitespace_denied: "gh api graphql -f query='  mutation{addStar}'",
        api_input_denied: "gh api repos/o/r/rulesets --input file.json",
        api_header_authorization_denied: "gh api repos/o/r/pulls -H 'Authorization: token ghp_xxx'",
        api_header_content_type_denied: "gh api repos/o/r/pulls -H 'Content-Type: application/json'",
        api_header_long_auth_denied: "gh api repos/o/r/pulls --header 'Authorization: Bearer xxx'",
        api_header_missing_value_denied: "gh api repos/o/r/pulls -H",
        api_header_no_colon_denied: "gh api repos/o/r/pulls -H 'Accept'",
        api_header_compact_denied: "gh api repos/o/r/pulls -HAuthorization:token",
        api_method_eq_patch_denied: "gh api repos/o/r/pulls/1 --method=PATCH",
        api_xpost_short_denied: "gh api repos/o/r/pulls -XPOST",
        api_xpatch_short_denied: "gh api repos/o/r/pulls -XPATCH",
        api_unknown_flag_denied: "gh api repos/o/r/pulls --some-unknown-flag",
    }
}
