#!/usr/bin/env bash
set -euo pipefail

# ─────────────────────────────────────────────────────────────────────────────
# 20-project-setup.sh — New Project Bootstrap for SecureGit
#
# Bootstrap a new project or configure an existing one with securegit:
# repo initialization, language detection, .gitignore/.gitattributes
# generation, directory structure, hooks, security scan, and initial commit.
#
# Usage:
#   ./20-project-setup.sh                     # Interactive setup
#   ./20-project-setup.sh init [directory]     # Initialize new project
#   ./20-project-setup.sh configure            # Configure existing repo
#   ./20-project-setup.sh hooks                # Install hooks only
# ─────────────────────────────────────────────────────────────────────────────

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/lib/securegit-common.sh"

# NOTE: We do NOT call sg_require_repo here because this script can
# initialize a new repository from scratch.

# ─── Constants ───────────────────────────────────────────────────────────────
_SETUP_LOG=""  # Set after we know the project dir

# ─── Gitignore Templates ────────────────────────────────────────────────────

_gitignore_for_lang() {
    local lang="$1"

    # Common ignores for all projects
    cat <<'COMMON'
# ─── OS files ────────────────────────────────────────────
.DS_Store
Thumbs.db
*.swp
*.swo
*~
.directory

# ─── Editor / IDE ───────────────────────────────────────
.vscode/
.idea/
*.iml
.project
.classpath
.settings/
*.sublime-workspace
*.sublime-project

# ─── SecureGit ──────────────────────────────────────────
.securegit/patches/
.securegit/quality/

# ─── Environment / secrets ──────────────────────────────
.env
.env.local
.env.*.local
*.pem
*.key
*.p12
credentials.json
COMMON

    case "$lang" in
        rust)
            cat <<'RUST'

# ─── Rust ───────────────────────────────────────────────
/target/
**/*.rs.bk
Cargo.lock
*.pdb
RUST
            ;;
        go)
            cat <<'GO'

# ─── Go ─────────────────────────────────────────────────
/vendor/
*.exe
*.exe~
*.dll
*.so
*.dylib
*.test
*.out
go.work
GO
            ;;
        python)
            cat <<'PYTHON'

# ─── Python ─────────────────────────────────────────────
__pycache__/
*.py[cod]
*$py.class
*.so
*.egg-info/
dist/
build/
.eggs/
.venv/
venv/
env/
.tox/
.nox/
.pytest_cache/
.mypy_cache/
.ruff_cache/
htmlcov/
.coverage
.coverage.*
PYTHON
            ;;
        js)
            cat <<'JS'

# ─── JavaScript / TypeScript ────────────────────────────
node_modules/
dist/
build/
.next/
.nuxt/
.output/
.cache/
*.tsbuildinfo
.turbo/
coverage/
.nyc_output/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
JS
            ;;
        java)
            cat <<'JAVA'

# ─── Java ───────────────────────────────────────────────
*.class
*.jar
*.war
*.ear
target/
build/
.gradle/
out/
bin/
*.log
hs_err_pid*
JAVA
            ;;
        ruby)
            cat <<'RUBY'

# ─── Ruby ───────────────────────────────────────────────
/.bundle/
/vendor/bundle
*.gem
.byebug_history
/coverage/
/spec/reports/
/tmp/
/log/
RUBY
            ;;
        php)
            cat <<'PHP'

# ─── PHP ────────────────────────────────────────────────
/vendor/
composer.phar
.phpunit.result.cache
.php-cs-fixer.cache
/storage/
/bootstrap/cache/
PHP
            ;;
        c)
            cat <<'CLANG'

# ─── C / C++ ────────────────────────────────────────────
*.o
*.obj
*.so
*.dylib
*.dll
*.a
*.lib
*.exe
*.out
build/
cmake-build-*/
CMakeFiles/
CMakeCache.txt
Makefile
*.d
CLANG
            ;;
        *)
            cat <<'GENERIC'

# ─── Build output ───────────────────────────────────────
build/
dist/
out/
bin/
*.log
GENERIC
            ;;
    esac
}

# ─── Gitattributes Templates ────────────────────────────────────────────────

_gitattributes_for_lang() {
    local lang="$1"

    cat <<'COMMON'
# ─── Auto-detect text files and normalize line endings ──
* text=auto

# ─── Force LF for scripts and config ───────────────────
*.sh text eol=lf
*.bash text eol=lf
*.conf text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.toml text eol=lf
*.json text eol=lf
*.md text eol=lf
Makefile text eol=lf
Dockerfile text eol=lf

# ─── Binary files ──────────────────────────────────────
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.pdf binary
*.zip binary
*.tar.gz binary
*.woff binary
*.woff2 binary
*.ttf binary
*.eot binary
COMMON

    case "$lang" in
        rust)
            cat <<'RUST'

# ─── Rust ──────────────────────────────────────────────
*.rs text eol=lf diff=rust
Cargo.toml text eol=lf
Cargo.lock text eol=lf -diff
RUST
            ;;
        go)
            cat <<'GO'

# ─── Go ────────────────────────────────────────────────
*.go text eol=lf diff=golang
go.sum text eol=lf -diff
GO
            ;;
        python)
            cat <<'PYTHON'

# ─── Python ────────────────────────────────────────────
*.py text eol=lf diff=python
*.pyx text eol=lf
requirements*.txt text eol=lf
PYTHON
            ;;
        js)
            cat <<'JS'

# ─── JavaScript / TypeScript ──────────────────────────
*.js text eol=lf
*.ts text eol=lf
*.jsx text eol=lf
*.tsx text eol=lf
*.mjs text eol=lf
*.cjs text eol=lf
package-lock.json text eol=lf -diff
pnpm-lock.yaml text eol=lf -diff
yarn.lock text eol=lf -diff
JS
            ;;
        java)
            cat <<'JAVA'

# ─── Java ──────────────────────────────────────────────
*.java text eol=lf diff=java
*.kt text eol=lf
*.gradle text eol=lf
*.gradle.kts text eol=lf
*.jar binary
*.war binary
JAVA
            ;;
        ruby)
            cat <<'RUBY'

# ─── Ruby ──────────────────────────────────────────────
*.rb text eol=lf diff=ruby
Gemfile text eol=lf
Gemfile.lock text eol=lf -diff
*.gemspec text eol=lf
RUBY
            ;;
        php)
            cat <<'PHP'

# ─── PHP ───────────────────────────────────────────────
*.php text eol=lf diff=php
composer.lock text eol=lf -diff
PHP
            ;;
        c)
            cat <<'CLANG'

# ─── C / C++ ──────────────────────────────────────────
*.c text eol=lf diff=cpp
*.h text eol=lf diff=cpp
*.cpp text eol=lf diff=cpp
*.hpp text eol=lf diff=cpp
*.cc text eol=lf diff=cpp
CLANG
            ;;
    esac
}

# ─── Directory Structure Templates ──────────────────────────────────────────

_create_directory_structure() {
    local project_dir="$1"
    local lang="$2"

    case "$lang" in
        rust)
            # Cargo init handles the structure
            if [[ ! -f "$project_dir/Cargo.toml" ]]; then
                sg_info "Cargo.toml not found. Consider running: cargo init"
            fi
            mkdir -p "$project_dir/src" "$project_dir/tests" "$project_dir/benches"
            ;;
        go)
            mkdir -p "$project_dir/cmd" "$project_dir/internal" "$project_dir/pkg"
            mkdir -p "$project_dir/test" "$project_dir/docs"
            if [[ ! -f "$project_dir/go.mod" ]]; then
                sg_info "go.mod not found. Consider running: go mod init <module>"
            fi
            ;;
        python)
            local project_name
            project_name="$(basename "$project_dir" | tr '-' '_')"
            mkdir -p "$project_dir/$project_name" "$project_dir/tests"
            if [[ ! -f "$project_dir/$project_name/__init__.py" ]]; then
                touch "$project_dir/$project_name/__init__.py"
            fi
            if [[ ! -f "$project_dir/tests/__init__.py" ]]; then
                touch "$project_dir/tests/__init__.py"
            fi
            ;;
        js)
            mkdir -p "$project_dir/src" "$project_dir/test" "$project_dir/public"
            ;;
        java)
            mkdir -p "$project_dir/src/main/java" "$project_dir/src/main/resources"
            mkdir -p "$project_dir/src/test/java" "$project_dir/src/test/resources"
            ;;
        ruby)
            local project_name
            project_name="$(basename "$project_dir" | tr '-' '_')"
            mkdir -p "$project_dir/lib/$project_name" "$project_dir/spec" "$project_dir/bin"
            ;;
        php)
            mkdir -p "$project_dir/src" "$project_dir/tests" "$project_dir/public" "$project_dir/config"
            ;;
        c)
            mkdir -p "$project_dir/src" "$project_dir/include" "$project_dir/test" "$project_dir/build"
            ;;
        *)
            mkdir -p "$project_dir/src" "$project_dir/test" "$project_dir/docs"
            ;;
    esac
}

# ─── Workflows Config Generation ────────────────────────────────────────────

_generate_workflows_conf() {
    local project_dir="$1"
    local lang="$2"

    local test_cmd lint_cmd fmt_cmd build_cmd

    # Temporarily set project context for detection
    local old_lang="${SG_LANGUAGE:-}"
    SG_LANGUAGE="$lang"

    test_cmd="$(sg_detect_test_cmd)"
    lint_cmd="$(sg_detect_lint_cmd)"
    fmt_cmd="$(sg_detect_fmt_cmd)"
    build_cmd="$(sg_detect_build_cmd)"

    SG_LANGUAGE="$old_lang"

    mkdir -p "$project_dir/.securegit"

    cat > "$project_dir/.securegit/workflows.conf" <<EOF
# securegit workflows.conf — Project-specific configuration
# Generated by 20-project-setup.sh on $(date -Iseconds)

# ─── Project ──────────────────────────────────────────────
SG_LANGUAGE="${lang}"

# ─── Quality commands (auto-detected, customize as needed) ─
SG_TEST_CMD="${test_cmd}"
SG_LINT_CMD="${lint_cmd}"
SG_FMT_CMD="${fmt_cmd}"
SG_BUILD_CMD="${build_cmd}"

# ─── Branch conventions ──────────────────────────────────
SG_PROTECTED_BRANCHES="main master develop staging production"
# SG_DEFAULT_BRANCH=""

# ─── Commit conventions ──────────────────────────────────
SG_COMMIT_TYPES="feat fix docs style refactor perf test build ci chore revert"
# SG_REQUIRE_TICKET="false"
# SG_TICKET_PATTERN="[A-Z]+-[0-9]+"

# ─── Quality gates ───────────────────────────────────────
SG_PRE_COMMIT_SCAN="true"
SG_PRE_PUSH_SCAN="true"
SG_MAX_DIFF_LINES="200"

# ─── Environment pipeline ────────────────────────────────
SG_ENVIRONMENTS="development staging production"
SG_ENV_BRANCHES="development=develop staging=staging production=main"

# ─── Multi-repo ──────────────────────────────────────────
# SG_WORKSPACE_DIR=""
# SG_REPO_GROUP=""
EOF
}

# ─── Operations ──────────────────────────────────────────────────────────────

op_init() {
    local project_dir="${1:-}"

    sg_header "New Project Setup"

    # Determine project directory
    if [[ -z "$project_dir" ]]; then
        project_dir="$(sg_prompt "Project directory (absolute path or name)" ".")"
    fi

    # Resolve relative paths
    if [[ "$project_dir" != /* ]]; then
        project_dir="$(pwd)/$project_dir"
    fi

    # Create directory if it doesn't exist
    if [[ ! -d "$project_dir" ]]; then
        sg_info "Creating directory: $project_dir"
        if ! sg_confirm "Create project directory?"; then
            return 0
        fi
        mkdir -p "$project_dir"
    fi

    # Check if already a git repo
    local is_existing_repo="false"
    if git -C "$project_dir" rev-parse --is-inside-work-tree &>/dev/null; then
        is_existing_repo="true"
        sg_info "Directory is already a git repository."
    fi

    _SETUP_LOG="$project_dir/.securegit/setup.log"

    # Detect or choose language
    local lang=""
    if [[ "$is_existing_repo" == "true" ]]; then
        cd "$project_dir"
        lang="$(sg_detect_language)"
        sg_info "Detected language: $lang"
    fi

    if [[ -z "$lang" ]] || [[ "$lang" == "generic" ]]; then
        local lang_options=("rust" "go" "python" "js" "java" "ruby" "php" "c" "generic")
        local choice
        choice="$(sg_menu "Select project language" "${lang_options[@]}")"
        lang="${lang_options[$((choice - 1))]}"
    else
        if ! sg_confirm "Use detected language ($lang)?"; then
            local lang_options=("rust" "go" "python" "js" "java" "ruby" "php" "c" "generic")
            local choice
            choice="$(sg_menu "Select project language" "${lang_options[@]}")"
            lang="${lang_options[$((choice - 1))]}"
        fi
    fi

    sg_info "Language: $lang"
    echo

    # Step 1: Initialize git repo if needed
    if [[ "$is_existing_repo" == "false" ]]; then
        sg_info "Step 1: Initializing git repository..."
        if _sg_cmd init "$project_dir" 2>/dev/null; then
            sg_success "Initialized securegit repository."
        else
            git init "$project_dir"
            sg_success "Initialized git repository."
        fi
    else
        sg_info "Step 1: Repository already initialized."
    fi

    cd "$project_dir"
    echo

    # Step 2: Generate .gitignore
    sg_info "Step 2: Generating .gitignore..."
    if [[ -f ".gitignore" ]]; then
        sg_warn ".gitignore already exists."
        if sg_confirm "Overwrite existing .gitignore?" "n"; then
            _gitignore_for_lang "$lang" > .gitignore
            sg_success "Generated .gitignore for $lang."
        else
            sg_info "Keeping existing .gitignore."
        fi
    else
        _gitignore_for_lang "$lang" > .gitignore
        sg_success "Generated .gitignore for $lang."
    fi
    echo

    # Step 3: Generate .gitattributes
    sg_info "Step 3: Generating .gitattributes..."
    if [[ -f ".gitattributes" ]]; then
        sg_warn ".gitattributes already exists."
        if sg_confirm "Overwrite existing .gitattributes?" "n"; then
            _gitattributes_for_lang "$lang" > .gitattributes
            sg_success "Generated .gitattributes for $lang."
        else
            sg_info "Keeping existing .gitattributes."
        fi
    else
        _gitattributes_for_lang "$lang" > .gitattributes
        sg_success "Generated .gitattributes for $lang."
    fi
    echo

    # Step 4: Create directory structure
    sg_info "Step 4: Creating directory structure..."
    if sg_confirm "Create standard directory structure for $lang?"; then
        _create_directory_structure "$project_dir" "$lang"
        sg_success "Directory structure created."
    else
        sg_info "Skipping directory structure."
    fi
    echo

    # Step 5: Initialize securegit
    sg_info "Step 5: Initializing securegit..."
    if command -v securegit &>/dev/null; then
        if _sg_cmd init 2>/dev/null; then
            sg_success "SecureGit initialized."
        else
            sg_warn "SecureGit init reported an issue (may already be initialized)."
        fi
    else
        sg_warn "securegit not found. Skipping securegit-specific initialization."
    fi
    echo

    # Step 6: Install hooks
    sg_info "Step 6: Installing git hooks..."
    if command -v securegit &>/dev/null; then
        if _sg_cmd hook install --all 2>/dev/null; then
            sg_success "All securegit hooks installed."
        else
            sg_warn "Hook installation reported an issue."
        fi
    else
        sg_warn "securegit not found. Skipping hook installation."
        sg_info "Install securegit and run: securegit hook install --all"
    fi
    echo

    # Step 7: Generate workflows.conf
    sg_info "Step 7: Generating .securegit/workflows.conf..."
    if [[ -f ".securegit/workflows.conf" ]]; then
        sg_warn ".securegit/workflows.conf already exists."
        if sg_confirm "Overwrite existing config?" "n"; then
            _generate_workflows_conf "$project_dir" "$lang"
            sg_success "Generated .securegit/workflows.conf."
        else
            sg_info "Keeping existing config."
        fi
    else
        _generate_workflows_conf "$project_dir" "$lang"
        sg_success "Generated .securegit/workflows.conf."
    fi
    echo

    # Step 8: Run initial security scan
    sg_info "Step 8: Running initial security scan..."
    if _sg_cmd scan "$project_dir" 2>/dev/null; then
        sg_success "Initial security scan passed."
    else
        sg_warn "Security scan found issues or securegit not available."
    fi
    echo

    # Step 9: Create initial commit
    sg_info "Step 9: Creating initial commit..."
    local has_commits="false"
    if git rev-parse HEAD &>/dev/null; then
        has_commits="true"
    fi

    # Stage generated files
    local files_to_stage=()
    [[ -f ".gitignore" ]] && files_to_stage+=(".gitignore")
    [[ -f ".gitattributes" ]] && files_to_stage+=(".gitattributes")
    [[ -f ".securegit/workflows.conf" ]] && files_to_stage+=(".securegit/workflows.conf")

    if (( ${#files_to_stage[@]} > 0 )); then
        git add "${files_to_stage[@]}"

        # Stage any other new files
        local untracked
        untracked="$(git status --porcelain 2>/dev/null | grep '^??' | wc -l | tr -d ' ')"
        if (( untracked > 0 )); then
            if sg_confirm "Stage $untracked untracked file(s) for initial commit?"; then
                git add -A
            fi
        fi

        if [[ "$has_commits" == "false" ]]; then
            if sg_confirm "Create initial commit?"; then
                git commit -m "chore: initial project setup with securegit

- Generated .gitignore for $lang
- Generated .gitattributes
- Created project directory structure
- Configured securegit workflows"
                sg_success "Initial commit created."
            fi
        else
            if sg_confirm "Commit securegit configuration changes?"; then
                git commit -m "chore: configure securegit for $lang project

- Generated/updated .gitignore
- Generated/updated .gitattributes
- Configured securegit workflows"
                sg_success "Configuration commit created."
            fi
        fi
    else
        sg_info "No files to commit."
    fi
    echo

    # Step 10: Set up remote
    sg_info "Step 10: Remote configuration..."
    if sg_has_remote; then
        local remote_url
        remote_url="$(git remote get-url "${SG_PRIMARY_REMOTE:-origin}" 2>/dev/null || echo "?")"
        sg_info "Remote already configured: $remote_url"
    else
        local remote_url
        remote_url="$(sg_prompt "Remote URL (leave empty to skip)" "")"
        if [[ -n "$remote_url" ]]; then
            git remote add "${SG_PRIMARY_REMOTE:-origin}" "$remote_url"
            sg_success "Remote added: ${SG_PRIMARY_REMOTE:-origin} -> $remote_url"

            if sg_confirm "Push to remote?"; then
                local default_branch
                default_branch="$(git symbolic-ref --short HEAD 2>/dev/null || echo "main")"
                git push -u "${SG_PRIMARY_REMOTE:-origin}" "$default_branch" 2>/dev/null || true
            fi
        else
            sg_info "Skipping remote setup."
        fi
    fi

    # Save setup log
    mkdir -p "$(dirname "$_SETUP_LOG")"
    {
        echo "# SecureGit Project Setup Log"
        echo "# Date: $(date -Iseconds)"
        echo "# Language: $lang"
        echo "# Directory: $project_dir"
        echo ""
        echo "Steps completed:"
        echo "  1. Git repository initialized"
        echo "  2. .gitignore generated ($lang)"
        echo "  3. .gitattributes generated ($lang)"
        echo "  4. Directory structure created"
        echo "  5. SecureGit initialized"
        echo "  6. Git hooks installed"
        echo "  7. Workflows config generated"
        echo "  8. Initial security scan completed"
        echo "  9. Initial commit created"
        echo " 10. Remote configured"
    } > "$_SETUP_LOG"

    # Show summary
    _show_summary "$project_dir" "$lang"
}

op_configure() {
    sg_header "Configure Existing Repository"

    local project_dir
    project_dir="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"

    if ! git -C "$project_dir" rev-parse --is-inside-work-tree &>/dev/null; then
        sg_die "Not inside a git repository. Use 'init' to create a new project."
    fi

    cd "$project_dir"

    local lang
    lang="$(sg_detect_language)"
    sg_info "Repository: $project_dir"
    sg_info "Detected language: $lang"

    if ! sg_confirm "Use detected language ($lang)?"; then
        local lang_options=("rust" "go" "python" "js" "java" "ruby" "php" "c" "generic")
        local choice
        choice="$(sg_menu "Select project language" "${lang_options[@]}")"
        lang="${lang_options[$((choice - 1))]}"
    fi
    echo

    # Offer to generate/update each config file
    if sg_confirm "Generate/update .gitignore?"; then
        if [[ -f ".gitignore" ]]; then
            sg_warn "Existing .gitignore will be overwritten."
            if sg_confirm "Continue?"; then
                _gitignore_for_lang "$lang" > .gitignore
                sg_success "Generated .gitignore."
            fi
        else
            _gitignore_for_lang "$lang" > .gitignore
            sg_success "Generated .gitignore."
        fi
    fi

    if sg_confirm "Generate/update .gitattributes?"; then
        if [[ -f ".gitattributes" ]]; then
            sg_warn "Existing .gitattributes will be overwritten."
            if sg_confirm "Continue?"; then
                _gitattributes_for_lang "$lang" > .gitattributes
                sg_success "Generated .gitattributes."
            fi
        else
            _gitattributes_for_lang "$lang" > .gitattributes
            sg_success "Generated .gitattributes."
        fi
    fi

    if sg_confirm "Generate .securegit/workflows.conf?"; then
        _generate_workflows_conf "$project_dir" "$lang"
        sg_success "Generated .securegit/workflows.conf."
    fi

    # Install hooks
    if command -v securegit &>/dev/null; then
        echo
        if sg_confirm "Install securegit hooks?"; then
            if _sg_cmd hook install --all 2>/dev/null; then
                sg_success "All hooks installed."
            else
                sg_warn "Hook installation reported an issue."
            fi
        fi
    fi

    # Run scan
    echo
    if sg_confirm "Run security scan?"; then
        _sg_cmd scan "$project_dir" 2>/dev/null || true
    fi

    echo
    _show_summary "$project_dir" "$lang"
}

op_hooks() {
    sg_header "Install SecureGit Hooks"

    if ! git rev-parse --is-inside-work-tree &>/dev/null; then
        sg_die "Not inside a git repository."
    fi

    if ! command -v securegit &>/dev/null; then
        sg_die "securegit is not installed. Install from: https://github.com/jfrog/securegit"
    fi

    sg_info "Installing all securegit hooks..."
    if _sg_cmd hook install --all 2>/dev/null; then
        sg_success "All hooks installed."
    else
        sg_error "Hook installation failed."
        return 1
    fi

    # List installed hooks
    echo
    sg_info "Installed hooks:"
    local hooks_dir
    hooks_dir="$(git rev-parse --git-dir)/hooks"
    if [[ -d "$hooks_dir" ]]; then
        local hook_file
        for hook_file in "$hooks_dir"/*; do
            [[ -f "$hook_file" ]] && [[ -x "$hook_file" ]] || continue
            local hook_name
            hook_name="$(basename "$hook_file")"
            # Skip sample hooks
            [[ "$hook_name" == *.sample ]] && continue
            printf "  ${_C_GREEN}+${_C_RESET} %s\n" "$hook_name"
        done
    fi
}

# ─── Summary Display ────────────────────────────────────────────────────────

_show_summary() {
    local project_dir="$1"
    local lang="$2"

    sg_header "Setup Summary"

    printf "  ${_C_BOLD}Project:${_C_RESET}    %s\n" "$project_dir"
    printf "  ${_C_BOLD}Language:${_C_RESET}    %s\n" "$lang"

    local branch
    branch="$(git -C "$project_dir" symbolic-ref --short HEAD 2>/dev/null || echo "?")"
    printf "  ${_C_BOLD}Branch:${_C_RESET}     %s\n" "$branch"

    local remote_url
    remote_url="$(git -C "$project_dir" remote get-url "${SG_PRIMARY_REMOTE:-origin}" 2>/dev/null || echo "none")"
    printf "  ${_C_BOLD}Remote:${_C_RESET}     %s\n" "$remote_url"

    echo
    sg_info "Files created/updated:"
    local check_files=(".gitignore" ".gitattributes" ".securegit/workflows.conf")
    for f in "${check_files[@]}"; do
        if [[ -f "$project_dir/$f" ]]; then
            printf "  ${_C_GREEN}+${_C_RESET} %s\n" "$f"
        fi
    done

    # Check hooks
    local hooks_dir
    hooks_dir="$(git -C "$project_dir" rev-parse --git-dir 2>/dev/null)/hooks"
    local hook_count=0
    if [[ -d "$hooks_dir" ]]; then
        local hook_file
        for hook_file in "$hooks_dir"/*; do
            [[ -f "$hook_file" ]] && [[ -x "$hook_file" ]] && [[ "$(basename "$hook_file")" != *.sample ]] && (( hook_count++ )) || true
        done
    fi
    printf "  ${_C_GREEN}+${_C_RESET} %d git hook(s) installed\n" "$hook_count"

    echo
    sg_info "Detected commands:"
    local old_lang="${SG_LANGUAGE:-}"
    SG_LANGUAGE="$lang"
    printf "  ${_C_DIM}Test:     %s${_C_RESET}\n" "$(sg_detect_test_cmd)"
    printf "  ${_C_DIM}Lint:     %s${_C_RESET}\n" "$(sg_detect_lint_cmd)"
    printf "  ${_C_DIM}Format:   %s${_C_RESET}\n" "$(sg_detect_fmt_cmd)"
    printf "  ${_C_DIM}Build:    %s${_C_RESET}\n" "$(sg_detect_build_cmd)"
    SG_LANGUAGE="$old_lang"

    echo
    sg_info "Next steps:"
    printf "  1. Review and customize .securegit/workflows.conf\n"
    printf "  2. Run quality checks: ./18-quality-check.sh quick\n"
    printf "  3. Start coding and use securegit for safe commits\n"
    if [[ "$remote_url" == "none" ]]; then
        printf "  4. Add a remote: git remote add origin <url>\n"
    fi
}

# ─── CLI Shortcut Handling ───────────────────────────────────────────────────

case "${1:-}" in
    init)
        shift
        op_init "${1:-}"
        exit 0
        ;;
    configure)
        op_configure
        exit 0
        ;;
    hooks)
        op_hooks
        exit 0
        ;;
    "")
        ;; # Fall through to interactive menu
    *)
        sg_die "Unknown command: $1. Use: init, configure, hooks"
        ;;
esac

# ─── Interactive Menu ────────────────────────────────────────────────────────

choice="$(sg_menu "SecureGit Project Setup" \
    "Initialize new project" \
    "Configure existing repository" \
    "Install hooks only" \
    "Quit"
)"

case "$choice" in
    1) op_init "" ;;
    2) op_configure ;;
    3) op_hooks ;;
    4) sg_info "Goodbye."; exit 0 ;;
esac
