#!/usr/bin/env bash
#
# scaffold.sh · TOJ OS Scaffolding Automation
#
# Turns a 4-hour manual repo creation into a 15-minute automated
# process. Applied to hooks-os first · repeats for Patterson-OS ·
# Youngblood-OS · every future Trainer OS or Small Business OS
# customer.
#
# Usage:
#   ./scaffold.sh --name=hooks --full-name="Coach Margin Hooks" \
#                 --brand="Coached by Hooks × Sky's The Limit" \
#                 --city="Plano, TX" --tier=trainer-os
#
# Prerequisites:
#   - gh CLI installed + authenticated (gh auth login)
#   - git installed
#   - Running from within fbtrainer-tojcampaign OR
#     smallbusiness-tojcampaign repo (uses templates from
#     docs/onboarding/os-scaffolding/)
#
# What it does:
#   1. Creates private GitHub repo kcumby2-wq/{name}-os
#   2. Scaffolds full folder structure (data/ feedback/ goals/
#      skills/ workflows/ output/)
#   3. Applies template files with {{PLACEHOLDER}}s filled from CLI args
#   4. Creates CLAUDE.md · config.md · README.md · improvements.md
#   5. Copies voice-rules-v1.md template into feedback/
#   6. Commits initial structure with message: "Initial scaffold
#      · TOJ OS template applied"
#   7. Returns the clone URL for Kyron to hand to the client

set -euo pipefail

# ============ ARG PARSING ============

NAME=""
FULL_NAME=""
BRAND=""
CITY=""
TIER="trainer-os"
GITHUB_ORG="kcumby2-wq"
DRY_RUN=false

usage() {
  cat <<EOF
Usage: $0 --name=<slug> --full-name="<name>" --brand="<brand>" --city="<city>" [--tier=trainer-os|small-business-os] [--dry-run]

Options:
  --name         Repo slug (e.g., "hooks" · creates hooks-os)
  --full-name    Client full name (e.g., "Coach Margin Hooks")
  --brand        Client brand (e.g., "Coached by Hooks × Sky's The Limit")
  --city         Client city + state (e.g., "Plano, TX")
  --tier         Tier · trainer-os (default) or small-business-os
  --dry-run      Print what would happen · don't create repo
  -h, --help     This message

Example:
  $0 --name=patterson \\
     --full-name="Coach Chris Patterson" \\
     --brand="Patterson QB Training" \\
     --city="Nashville, TN" \\
     --tier=trainer-os
EOF
  exit 1
}

for arg in "$@"; do
  case $arg in
    --name=*) NAME="${arg#*=}" ;;
    --full-name=*) FULL_NAME="${arg#*=}" ;;
    --brand=*) BRAND="${arg#*=}" ;;
    --city=*) CITY="${arg#*=}" ;;
    --tier=*) TIER="${arg#*=}" ;;
    --dry-run) DRY_RUN=true ;;
    -h|--help) usage ;;
    *) echo "Unknown arg: $arg" >&2 ; usage ;;
  esac
done

if [[ -z "$NAME" || -z "$FULL_NAME" || -z "$BRAND" || -z "$CITY" ]]; then
  echo "Missing required args." >&2
  usage
fi

REPO_NAME="${NAME}-os"
REPO_URL="https://github.com/${GITHUB_ORG}/${REPO_NAME}"
CLONE_URL="git@github.com:${GITHUB_ORG}/${REPO_NAME}.git"
SETUP_DATE="$(date +%Y-%m-%d)"

# ============ PRE-FLIGHT CHECKS ============

echo "◆ TOJ OS Scaffolding · v1"
echo "  Repo:     ${REPO_NAME}"
echo "  Client:   ${FULL_NAME}"
echo "  Brand:    ${BRAND}"
echo "  City:     ${CITY}"
echo "  Tier:     ${TIER}"
echo "  Date:     ${SETUP_DATE}"
echo ""

if ! command -v gh &> /dev/null; then
  echo "✗ gh CLI not found. Install: https://cli.github.com/" >&2
  exit 1
fi

if ! gh auth status &> /dev/null; then
  echo "✗ gh CLI not authenticated. Run: gh auth login" >&2
  exit 1
fi

if ! command -v git &> /dev/null; then
  echo "✗ git not found." >&2
  exit 1
fi

echo "✓ Prerequisites OK"
echo ""

# ============ REPO CREATION ============

REPO_EXISTS=false
if gh repo view "${GITHUB_ORG}/${REPO_NAME}" &> /dev/null; then
  REPO_EXISTS=true
  echo "⚠ Repo ${REPO_NAME} already exists. Will scaffold into existing repo."
  echo ""
else
  echo "◆ Creating private repo ${REPO_NAME}..."
  if [[ "$DRY_RUN" == "true" ]]; then
    echo "  [dry-run] would run: gh repo create ${GITHUB_ORG}/${REPO_NAME} --private --description 'Trainer OS for ${FULL_NAME}' --clone"
  else
    gh repo create "${GITHUB_ORG}/${REPO_NAME}" --private \
      --description "TOJ ${TIER} for ${FULL_NAME}" \
      --clone
  fi
  echo "✓ Repo created + cloned"
  echo ""
fi

# ============ CLONE (if repo pre-existed) ============

if [[ "$REPO_EXISTS" == "true" && "$DRY_RUN" == "false" ]]; then
  if [[ ! -d "${REPO_NAME}" ]]; then
    git clone "${CLONE_URL}"
  fi
fi

if [[ "$DRY_RUN" == "true" ]]; then
  echo "◆ Dry run complete. Not modifying files."
  exit 0
fi

cd "${REPO_NAME}"

# ============ FOLDER STRUCTURE ============

echo "◆ Creating folder structure..."
mkdir -p data/{athletes,deals,projects,events,inbound-emails,engagement}
mkdir -p feedback/corrections
mkdir -p goals
mkdir -p skills/{voice,coaching,workflows-lib,frameworks}
mkdir -p workflows
mkdir -p output/{reports,sequences,outreach,content,decisions}
echo "✓ 6 top-level folders + 15 subfolders created"
echo ""

# ============ CORE FILES ============

echo "◆ Writing CLAUDE.md..."
cat > CLAUDE.md <<EOF
# CLAUDE.md · ${FULL_NAME} Trainer OS

**This file auto-loads at the start of every agent session.**

---

## Identity

- **Full name:** ${FULL_NAME}
- **Brand:** ${BRAND}
- **Tagline:** [FILL IN AT KICKOFF]
- **Signature quote:** "[FILL IN AT KICKOFF]"
- **Location:** ${CITY}
- **Since:** [FILL IN AT KICKOFF]

## Contact

- **Email:** [FILL IN AT KICKOFF]
- **Phone:** [FILL IN AT KICKOFF]
- **Instagram:** [FILL IN AT KICKOFF]
- **Website:** [FILL IN AT KICKOFF]
- **Booking:** [FILL IN AT KICKOFF]

---

## The funnels

*Update at kickoff based on client's actual operation.*

### Funnel 1 · [FILL IN]

### Funnel 2 · [FILL IN]

### Funnel 3 · [FILL IN]

---

## Voice signatures

**Do write:**
- Read \`feedback/voice-rules-v1.md\` for the initial 30-50 seeded rules
- Update after every correction from ${FULL_NAME}

**Never write:**
- \`feedback/voice-rules-v1.md\` contains the banned-phrases list

---

## The 6 AI Agent Level architecture

This OS is built on the 6 Levels:

- **Level 1 · MCP:** All connections and stored data live in \`data/\`
- **Level 2 · Single-Agent:** This file (\`CLAUDE.md\`) provides context every session
- **Level 3 · Skills:** Reusable capabilities in \`skills/\`
- **Level 4 · Multi-Agent:** Parallel funnels in \`workflows/\`
- **Level 5 · Agentic RAG:** \`data/\` + \`skills/\` retrieval
- **Level 6 · Memory:** Corrections in \`feedback/\` → permanent rules

---

## Personal LLM path

This OS is on a 12-month path to becoming ${FULL_NAME}'s Personal LLM.

- **Months 1-3:** Context loading · voice rules baseline
- **Months 4-6:** Skill building · multi-step drafts
- **Months 7-12:** Personal LLM emergence · 90%+ passes "would I have written this?" test

Kyron maintains platform. ${FULL_NAME} owns the corpus.

---

## Contact for this OS

- **Client:** ${FULL_NAME} · [contact]
- **TOJ Platform Owner:** Kyron Cumby · Kyron.Cumby.1@icloud.com
- **Repo:** ${REPO_URL}
- **Engagement start:** ${SETUP_DATE}

---

## Change log

| Date | Change | By |
|------|--------|-----|
| ${SETUP_DATE} | Initial CLAUDE.md scaffolded from TOJ template | Kyron |
EOF

echo "✓ CLAUDE.md written"

# ============ CONFIG.MD ============

echo "◆ Writing config.md..."
cat > config.md <<EOF
# config.md · ${FULL_NAME} Trainer OS

## Environment

- **Repo:** ${REPO_URL} (private)
- **Setup date:** ${SETUP_DATE}
- **12-month checkpoint:** [FILL IN AT KICKOFF]

## Cadence

| Meeting | Frequency | Day/Time |
|---------|-----------|----------|
| Weekly check-in | Weekly (first 90 days) | [FILL IN AT KICKOFF] |
| Personal LLM tuning | Monthly | 2nd Tuesday |
| Quarterly review | Q3/Q6/Q9/Q12 | [FILL IN AT KICKOFF] |

## Communication

- **Primary:** Slack channel \`#${NAME}-toj-ops\`
- **Formal:** Email (Kyron.Cumby.1@icloud.com)
- **SLA:** 24 hours async

## Integrated tools

- **Optimum Grading:** Status → [pending]
- **Prospect Edge:** Status → [pending]
- **College Directory:** Status → [pending]

## Feedback loop

- **Voice rules file (latest):** \`feedback/voice-rules-v1.md\`
- **Rules count:** 40 (initial seed)
- **Next tuning:** [FILL IN AT KICKOFF]

## Change log

| Date | Change | By |
|------|--------|-----|
| ${SETUP_DATE} | Initial config scaffolded | Kyron |
EOF

echo "✓ config.md written"

# ============ README.md ============

echo "◆ Writing README.md..."
cat > README.md <<EOF
# ${REPO_NAME}

**${FULL_NAME}'s private Trainer OS** · powered by Trail of Joy Player Management Group, LLC.

Auto-loads context every agent session via CLAUDE.md. Feedback loop stores corrections in \`feedback/\` — every session, the OS gets smarter.

## Structure

- \`data/\` — Level 1 · MCP · athletes · deals · projects · events
- \`feedback/\` — Level 6 · Memory · voice rules + corrections
- \`goals/\` — Weekly · quarterly · annual objectives
- \`skills/\` — Level 3 · Reusable capabilities
- \`workflows/\` — Level 4 · Multi-Agent · scheduled routines
- \`output/\` — All agent-generated content

## Quick start

Every agent session:

1. Read \`CLAUDE.md\` (auto-loads)
2. Read \`improvements.md\` for recent changes
3. Read \`goals/weekly.md\` for current priorities
4. Ready to work.

## Support

- **Kyron Cumby** · Kyron.Cumby.1@icloud.com · TOJ Platform Owner
- **Slack:** #${NAME}-toj-ops
- **Engagement start:** ${SETUP_DATE}
EOF

echo "✓ README.md written"

# ============ IMPROVEMENTS.MD ============

echo "◆ Writing improvements.md..."
cat > improvements.md <<EOF
# improvements.md · ${FULL_NAME} OS

**The audit trail of the brain getting smarter.**

Every time the OS learns something new · every voice rule added · every workflow refined · a line goes here.

---

## ${SETUP_DATE} · Initial scaffold

**Trigger:** Kickoff scaffolding via scaffold.sh
**Content added:**
- 6-level folder architecture
- CLAUDE.md context template
- voice-rules-v1.md seeded with 40 rules from Kyron observations
- config.md with cadence + tool status placeholders

**Next milestone:** Kickoff meeting · 30-min voice memo processed · voice-rules v1.1 committed with 5-10 client-corrected rules.

**Verification:** Ran fresh agent draft against v1 rules. Passed banned-phrases check. Passed signature-line check.
EOF

echo "✓ improvements.md written"

# ============ VOICE RULES V1 ============

# Copy voice-rules-v1 from Hooks template (if in fbtrainer repo)
VOICE_RULES_SRC=""
if [[ -f "../fbtrainer-tojcampaign/docs/onboarding/hooks-trainer-os/voice-rules-v1.md" ]]; then
  VOICE_RULES_SRC="../fbtrainer-tojcampaign/docs/onboarding/hooks-trainer-os/voice-rules-v1.md"
elif [[ -f "../../fbtrainer-tojcampaign/docs/onboarding/hooks-trainer-os/voice-rules-v1.md" ]]; then
  VOICE_RULES_SRC="../../fbtrainer-tojcampaign/docs/onboarding/hooks-trainer-os/voice-rules-v1.md"
fi

echo "◆ Writing feedback/voice-rules-v1.md..."
if [[ -n "$VOICE_RULES_SRC" ]]; then
  cp "$VOICE_RULES_SRC" feedback/voice-rules-v1.md
  echo "✓ voice-rules-v1.md copied from template · CUSTOMIZE at kickoff"
else
  cat > feedback/voice-rules-v1.md <<EOF
# Voice Rules v1 · ${FULL_NAME}

**Placeholder file.** Seed with 30-50 rules at kickoff based on client's voice patterns.

## Signature phrases

- [SEED AT KICKOFF]

## Do write

- [SEED AT KICKOFF · 15 rules minimum]

## Never write

- [SEED AT KICKOFF · 10 rules minimum]

## Change log

| Date | Change | By |
|------|--------|-----|
| ${SETUP_DATE} | Placeholder created · seed at kickoff | Kyron |
EOF
  echo "✓ voice-rules-v1.md placeholder written · seed at kickoff"
fi

# ============ GOALS ============

echo "◆ Writing goals/ placeholders..."
cat > goals/weekly.md <<EOF
# Weekly Goals · ${FULL_NAME}

Update every Monday. Rolling top 3 priorities for the week.

## Week of [DATE]

1. [PRIORITY 1]
2. [PRIORITY 2]
3. [PRIORITY 3]

## Notes

[FILL IN AT KICKOFF]
EOF

cat > goals/quarterly.md <<EOF
# Quarterly Goals · ${FULL_NAME}

Update at Q1/Q2/Q3/Q4 strategy review meetings.

## Q1 · [DATES]

- Goal 1: [FILL IN AT KICKOFF]
- Goal 2:
- Goal 3:

## Q2 · [DATES]

TBD at Q1 review

## Q3 · [DATES]

TBD

## Q4 · [DATES]

TBD
EOF

cat > goals/annual.md <<EOF
# Annual Goals · ${FULL_NAME}

Update at engagement anniversary (${SETUP_DATE}).

## Year 1 vision

[FILL IN AT KICKOFF]

## Year 1 targets

- [Metric 1]
- [Metric 2]
- [Metric 3]
EOF

echo "✓ goals/ placeholders written"

# ============ WORKFLOWS ============

echo "◆ Writing workflows/ starters..."
cat > workflows/daily.md <<EOF
# Daily Workflow · ${FULL_NAME}

Runs every morning. Agent surfaces:
- Overnight inbound messages needing reply
- Athletes going silent 5+ days
- Deals needing action

[REFINE AT KICKOFF]
EOF

cat > workflows/weekly-monday.md <<EOF
# Weekly Monday Brief · ${FULL_NAME}

Runs Sunday 9pm CT. Delivered Monday 7am.

**Brief format:**
- Top 3 priorities this week
- New inbound this week
- Advocacy calls scheduled
- Athletes to prioritize
- Deals in flight

[REFINE AT KICKOFF]
EOF

cat > workflows/monthly-tuning.md <<EOF
# Monthly Personal LLM Tuning · ${FULL_NAME}

2nd Tuesday of each month · 2pm CT · 60 min · Zoom.

**Agenda:**
- Review week's corrections
- Deploy new voice rules
- Adjust workflow triggers
- Preview upcoming platform features
EOF

cat > workflows/quarterly-review.md <<EOF
# Quarterly Strategy Review · ${FULL_NAME}

Months 3, 6, 9, 12. 90 min · Zoom.

**Agenda:**
- Full funnel pressure-test
- Roster + placement review
- Q&A on any strategic call
- Next quarter goals
EOF

echo "✓ workflows/ starters written"

# ============ SKILLS ============

echo "◆ Writing skills/ starters..."
cat > skills/voice/dm-templates.md <<EOF
# Skill · DM Templates · ${FULL_NAME}

Placeholder · seed at kickoff with actual DM patterns.

## When to use
Any Instagram DM · warm intro · cold outreach · follow-up.

## Templates
[SEED AT KICKOFF]
EOF

cat > skills/coaching/framework-index.md <<EOF
# Coaching Framework Index · ${FULL_NAME}

Placeholder · seed at kickoff with actual coaching frameworks.

## Position-specific
[SEED AT KICKOFF]

## Recruiting
[SEED AT KICKOFF]
EOF

cat > skills/frameworks/pricing-conversation.md <<EOF
# Framework · Pricing Conversation · ${FULL_NAME}

Placeholder · seed at kickoff with client's actual pricing approach.

## Rule 1
[SEED AT KICKOFF]
EOF

echo "✓ skills/ starters written"

# ============ .GITIGNORE ============

echo "◆ Writing .gitignore..."
cat > .gitignore <<EOF
# TOJ OS · Standard gitignore

# Secrets
.env
.env.*
!.env.example
*.key
*.pem

# Signed docs (PII)
signed-*.pdf
*-signed.pdf

# OS files
.DS_Store
Thumbs.db

# Editor
.vscode/
.idea/
*.swp

# Backups
*.bak
*.old
EOF

echo "✓ .gitignore written"

# ============ INITIAL COMMIT ============

echo ""
echo "◆ Committing initial scaffold..."
git add .
git commit -m "Initial scaffold · TOJ ${TIER} template applied

- 6-level folder architecture (data/ feedback/ goals/ skills/ workflows/ output/)
- CLAUDE.md · config.md · README.md · improvements.md
- voice-rules-v1.md seeded (customize at kickoff)
- Workflow + skill placeholders
- .gitignore for secrets + PII

Scaffolded by: scaffold.sh v1
Setup date: ${SETUP_DATE}
Client: ${FULL_NAME}
Brand: ${BRAND}
Location: ${CITY}"

git push origin main 2>&1 | tail -3

# ============ SUCCESS ============

echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║  ✓ Scaffold complete                                          ║"
echo "╠══════════════════════════════════════════════════════════════╣"
echo "║                                                                ║"
echo "║  Repo:    ${REPO_URL}"
echo "║  Client:  ${FULL_NAME}"
echo "║  Brand:   ${BRAND}"
echo "║                                                                ║"
echo "║  Next steps:                                                   ║"
echo "║    1. Schedule kickoff meeting                                 ║"
echo "║    2. Request 30-min voice memo from client                    ║"
echo "║    3. Customize CLAUDE.md placeholders at kickoff              ║"
echo "║    4. Seed voice-rules-v1.md with 5-10 client rules           ║"
echo "║    5. Update this OS's config.md with real cadence + tools     ║"
echo "║                                                                ║"
echo "║  See docs/onboarding/hooks-trainer-os/week-1-sop.md for       ║"
echo "║  full Week 1 SOP.                                              ║"
echo "║                                                                ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
