#!/usr/bin/env bash
# WTM PR Library - PR template generation and creation

# Generate a PR body from commit history and file stats
# Usage: generate_pr_body <worktree> <base_branch>
# Output: markdown PR body string
generate_pr_body() {
  local worktree="$1"
  local base_branch="${2:-main}"

  local commits changed_files session_id
  commits=$(git -C "${worktree}" log --oneline "origin/${base_branch}..HEAD" 2>/dev/null || echo "(no commits)")
  changed_files=$(git -C "${worktree}" diff --stat "origin/${base_branch}..HEAD" 2>/dev/null || echo "(no changes)")
  session_id=$(basename "${worktree}")

  local template_path="${WTM_HOME}/templates/pr_template.md"

  if [[ -f "${template_path}" ]]; then
    local body
    body=$(cat "${template_path}")
    body="${body//\$\{COMMITS\}/${commits}}"
    body="${body//\$\{CHANGED_FILES\}/${changed_files}}"
    body="${body//\$\{SESSION_ID\}/${session_id}}"
    echo "${body}"
  else
    # Fallback inline template
    cat <<EOF
## Summary

### Changes

${commits}

### Files Changed

\`\`\`
${changed_files}
\`\`\`

### Checklist

- [ ] Tests pass
- [ ] No new warnings
- [ ] Documentation updated (if applicable)
- [ ] Conventional commits used

---
Generated by WTM | Session: ${session_id}
EOF
  fi
}

# Push branch and create a PR via gh CLI
# Usage: create_pr <worktree> <base_branch> <title>
# Output: PR URL
create_pr() {
  local worktree="$1"
  local base_branch="${2:-main}"
  local title="$3"

  local current_branch
  current_branch=$(git -C "${worktree}" rev-parse --abbrev-ref HEAD 2>/dev/null)
  if [[ -z "${current_branch}" ]]; then
    log_error "Could not determine current branch in: ${worktree}"
    return 1
  fi

  log_info "Pushing branch '${current_branch}' to origin..."
  git -C "${worktree}" push -u origin "${current_branch}" || {
    log_error "Failed to push branch: ${current_branch}"
    return 1
  }

  log_info "Generating PR body..."
  local pr_body
  pr_body=$(generate_pr_body "${worktree}" "${base_branch}")

  log_info "Creating PR via gh CLI..."
  local pr_url
  pr_url=$(gh pr create \
    --base "${base_branch}" \
    --head "${current_branch}" \
    --title "${title}" \
    --body "${pr_body}" \
    2>&1)

  if [[ $? -ne 0 ]]; then
    log_error "Failed to create PR: ${pr_url}"
    return 1
  fi

  log_ok "PR created: ${pr_url}"
  echo "${pr_url}"
}

# Auto-generate a PR title from session info
# Usage: generate_pr_title <session_id>
# e.g., "project:feature-add-auth" -> "feat: add-auth"
generate_pr_title() {
  local session_id="$1"

  python3 -c "
import sys, re
session_id = '${session_id}'
# Strip project prefix (everything before ':')
if ':' in session_id:
    remainder = session_id.split(':', 1)[1]
else:
    remainder = session_id

# Split type and name on first '-'
parts = remainder.split('-', 1)
if len(parts) == 2:
    stype, name = parts
    # Map session types to commit types
    type_map = {
        'feature': 'feat',
        'feat':    'feat',
        'fix':     'fix',
        'bugfix':  'fix',
        'hotfix':  'fix',
        'docs':    'docs',
        'chore':   'chore',
        'refactor':'refactor',
        'test':    'test',
        'perf':    'perf',
    }
    commit_type = type_map.get(stype.lower(), stype.lower())
    print(f'{commit_type}: {name}')
else:
    print(remainder)
"
}
