#!/bin/bash
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
echo "Building docs/required + docs/optimal - generic names every project should have"
mkdir -p "$ROOT/docs/required" "$ROOT/docs/optimal" "$ROOT/docs/aistd"
BUILT_AT=$(date)

# REQUIRED 14 - every project must have
for name in "01.requirements" "02.ai.usage.guide" "03.chat.instructions" "ewizard.init" "frontend.overview" "frontend.files" "frontend.paths" "backend.overview" "backend.files" "backend.endpoints" "admin.overview" "auth.overview" "common.architecture" "common.files"; do
  case $name in
    "01.requirements") content="# 01 Requirements - Required
Common Header: APP_NAME={{project_name}} | APP_URL={{app_url}} | VERSION={{version}} | BUILT_AT=$BUILT_AT
Purpose: Single source truth for what project must do.
Generic Template Every Project:
- project_name (REQ): {{project_name}}
- project_path (REQ): {{project_path}}
- goals_primary (OPT): {{goals_primary}}
- constraints (OPT): {{constraints}}
- stakeholders (OPT): {{stakeholders}} - developer, admin, proj mgmt
- deliverables (OPT): {{deliverables}} - data/build/*.md + docs/aistd/aistd.*.md
- risks (OPT): {{risks}} - perms rbutareOld vs rbutare, hardcoded paths
- questions (OPT): {{questions}}
STD: structure same every app. CUSTOM: values {{}} per app." ;;
    "02.ai.usage.guide") content="# 02 AI Usage Guide - Required - REPLACES agents.md, ai_context.md, ai.rules.md, ai.setup.md, cheatsheet.md, golden_rules.md
Common Header: APP_NAME={{project_name}} | TYPE=required
Rules Every Project:
1 Common header APP_NAME APP_URL VERSION BUILT_AT in every file
2 Dot naming aistd.*.md lowercase no spaces
3 Paths chain \$dir=__DIR__; for(\$i=0;\$i<6;\$i++){ foreach([\"\$dir/../../system/php/paths.php\"] as \$p){ if(file_exists(\$p)){\$found=\$p; break 2;}} \$dir=dirname(\$dir);} require_once \$found; - no hardcoded /Users/
4 True vs Generic: Generic bad # placeholder no header. True good: header + real scan
5 BS5 5.3.3 fontawesome sidebar 260px sticky
6 Builder php/build.php JSON+templates+manifest+header → data/build + docs/aistd" ;;
    "03.chat.instructions") content="# 03 Chat Instructions - Required
Common Header: APP_NAME={{project_name}}
Flow: Read docs.manifest.json (6 sections 16 files) + form_fields.json (REQ project_name path OPT goals) + templates/*.template.md {{}} + scan frontend admin includes via RecursiveDirectoryIterator → build true md not generic → write both dirs" ;;
    "ewizard.init") content="# ewizard.init - Required
Init Prompt: BASE_ROOT=/Users/rbutare/websites BASE_URL=/apps APP_NAME={{project_name}} Read .env manifest form_fields defaults bootstrap=true dot naming data/wizard.json 777 data/build 777 docs/aistd 777 Build from templates + header + scan Paths chain no hardcoded UI navbar Wizard|Docs|Admin|Help sidebar contextual accordion breadcrumbs clickable tabs" ;;
    "frontend.overview") content="# Frontend Overview - Required
Scan: frontend/, templates/ - header.php BS5, navbar.php 4 sections, content-start.php d-flex flex-md-row sidebar 260px sticky top 56px flex-shrink-0 content flex-grow-1 min-width 0 overflow-x auto max-width 100% no glob for speed, content-end.php bootstrap.bundle.min.js" ;;
    "frontend.files") content="# Frontend Files - Required - True Scan
True scan via RecursiveDirectoryIterator frontend/ templates/ list actual files with size - not generic placeholder. Built by php/build.php inject real files + header" ;;
    "frontend.paths") content="# Frontend Paths - Required - Standard Fix
Standard Fix: \$dir=__DIR__; \$found=\"\"; for(\$i=0;\$i<6;\$i++){ foreach([\"\$dir/../../system/php/paths.php\"] as \$p){ if(file_exists(\$p)){\$found=\$p; break 2;}} \$dir=dirname(\$dir);} require_once \$found; - fixes hardcoded /Users/rbutare/websites/system/php/paths.php that fails + perms" ;;
    "backend.overview") content="# Backend Overview - Required
Scan: includes/, php/, config/ - bootstrap.php loads paths chain checks is_logged_in, build.php reads wizard.json + defaults + .env + manifest + templates replaces {{}} + header writes both dirs, save.php saves step, docs.manifest.json 6 sections defines 16 files, form_fields.json REQ/OPT, data/wizard.json steps completed" ;;
    "backend.files") content="# Backend Files - Required - True Scan
Actual backend files scan via RecursiveDirectoryIterator includes/ php/ config/ - lists real files + size" ;;
    "backend.endpoints") content="# Backend Endpoints - Required
GET ?section=wizard&step=1-10, ?section=docs&cat=all|requirements|wizard|frontend|admin|backend|auth|common&view=file.md, ?section=admin&tab=system|app|configs|templates|users|test|audit, ?section=help&page=faq|mapping|compare|guide|workflow, POST php/save.php, GET php/build.php Build All Now - all use APP_URL not hardcoded" ;;
    "admin.overview") content="# Admin Overview - Required
Admin split system/apps: System (paths, system env editable, audit report & fix all), App (app.env editable, JSON configs CRUD, templates CRUD, users, test summary PASS/FAIL). Some functions need terminal/sh documented, TBA future handle directly from UX via sh tools -m circular menu" ;;
    "auth.overview") content="# Auth Overview - Required
bootstrap.php is_logged_in() check, current_user(), redirect to login.php if !logged, uses paths chain not hardcoded. Standard vs custom: STD auth flow, CUSTOM user roles" ;;
    "common.architecture") content="# Common Architecture - Required
STD same every app: header APP_NAME APP_URL VERSION BUILT_AT, UI bootstrap fontawesome sidebar auto-collapse wizard 10 steps dot naming base_directory docs, paths chain 6 levels no hardcoded, auth is_logged_in, layout navbar sticky BS5 sidebar 240px responsive col-md-3 content col-md-9 same window viewer, manifest 6 sections, builder JSON+templates+manifest+header. CUSTOM per app: project_name path goals constraints stakeholders deliverables risks questions scan results" ;;
    "common.files") content="# Common Files - Required
List 23 true files: Required 14 (01.requirements,02.ai.usage.guide,03.chat.instructions,ewizard.init,wizard.overview,frontend.overview,frontend.files,frontend.paths,backend.overview,backend.files,backend.endpoints,admin.overview,auth.overview,common.architecture,common.files) + Optimal 15 (wizard.steps etc) = 29 total generic every project should have" ;;
  esac
  echo "$content" > "$ROOT/docs/required/$name.md"
  echo "Created required/$name.md"
done

# OPTIMAL 21 - optimal for wizard-like projects, generic every project should have
for name in "wizard.overview" "wizard.steps" "wizard.modules" "frontend.naming" "frontend.routing-map" "frontend.navigation-system" "backend.api" "backend.architecture" "admin.pages" "auth.flow" "auth.user-roles" "common.guide" "common.modules" "common.scan" "common.file-naming-rules" "common.coding-standards" "common.data-model" "common.security" "common.testing" "common.deployment" "common.web-access-architecture"; do
  case $name in
    "wizard.overview") content="# Wizard Overview - Optimal - Every project wizard type should have
Wizard pattern: Setup 1 REQ, Goals 2-4, People 5-6, Risks 7-8, Review 9-10, Build. Sidebar pick steps progress X/10" ;;
    "wizard.steps") content="# Wizard Steps - Optimal
Steps 1-10: 1 Setup REQ project_name path → wizard.json, 2 Goals Primary, 3 Constraints, 4 Goals Secondary, 5 Stakeholders, 6 Deliverables, 7 Risks, 8 Questions, 9 Review summary, 10 Build writes data/build + docs/aistd. Each saves stepX.completed" ;;
    "wizard.modules") content="# Wizard Modules - Optimal
Modules: pages/steps/step1.php...step10.php, php/save.php, php/build.php, data/wizard.json, form_fields.json defines fields per step" ;;
    "frontend.naming") content="# Frontend Naming - Optimal - From FILE.NAMING.RULES
Dot naming aistd.*.md lowercase no spaces, templates/*.template.md, stepX.php, docs/required/ docs/optimal/ docs/aistd/. No camelCase" ;;
    "frontend.routing-map") content="# Frontend Routing Map - Optimal - From ROUTING-MAP
?section=wizard|docs|admin|help & ?step=1-10 & ?cat=all|requirements|wizard|frontend|admin|backend|auth|common & ?view=file.md & ?tab=system|app|configs|templates|users|test|audit & ?page=faq|mapping|compare|guide|workflow. Router aiwizard.index.php header navbar content-start page content-end" ;;
    "frontend.navigation-system") content="# Frontend Navigation System - Optimal - From NAVIGATION-SYSTEM
Navbar major sections organized by category/type, sidenavbar supports sections in navbar contextual clean concise collapse/uncollapse accordion to focus reduce overwhelming info, clicking details provides info in content window same window, goal simplify UX organize around topic function category create flow. Sidebar 260px sticky top 56px flex-shrink-0 content flex-grow-1 min-width 0 overflow-x auto breadcrumbs clickable tabs data-bs-toggle=tab working" ;;
    "backend.api") content="# Backend API - Optimal
GET /php/build.php builds docs, POST /php/save.php step=1 data={}, GET /data/wizard.json progress, all JSON APP_ROOT no hardcoded" ;;
    "backend.architecture") content="# Backend Architecture - Optimal
Folder structure standard vs custom: BASE_ROOT system/php/paths.php chain, APP_ROOT config/ data/ docs/ pages/ templates/ php/ tools/. Manifest defines scan dirs, build.php scans via RecursiveDirectoryIterator, templates replace {{}} + header" ;;
    "admin.pages") content="# Admin Pages - Optimal
pages/admin/index.php tabs: system (paths, system env editable, audit report & fix all), app (app.env), configs (manifest form_fields defaults CRUD), templates (templates CRUD), users (current_user is_logged_in), test (PASS/FAIL summary), audit (missing perms hardcoded + Fix All At Once)" ;;
    "auth.flow") content="# Auth Flow - Optimal
login.php POST username/password → session current_user → bootstrap checks is_logged_in() → if !logged redirect to APP_URL/pages/login.php → else allow. Paths chain" ;;
    "auth.user-roles") content="# Auth User Roles - Optimal - USER-ROLES-AND-PERMISSIONS
Roles developer, admin, proj mgmt: developer setup wizard fix Steps2-8 maintain build.php scan paths chain, admin system/app split edit .env configs templates CRUD audit perms tests fix owner rbutareOld vs rbutare xattr -cr, proj mgmt fill wizard goals review build view Docs by category Help FAQ Mapping Compare Workflow" ;;
    "common.guide") content="# Common Guide - Optimal
Standard vs Customized: Standard same every app (header BS5 sidebar wizard 10 steps dot naming paths chain auth layout manifest builder). Custom per app (project_name path goals constraints stakeholders deliverables risks questions scan results)" ;;
    "common.modules") content="# Common Modules - Optimal
Modules: wizard (steps), frontend (templates), admin (pages), backend (php), auth (login), common (architecture guide files). Each defined in manifest with scan dirs and files" ;;
    "common.scan") content="# Common Scan - Optimal - COMMON/SCAN.MD
Scan via RecursiveDirectoryIterator true file lists: frontend/ → frontend.files.md true scan, includes/ php/ config/ → backend.files.md, admin/ → admin.pages.md, docs/ → common.files.md 23 list. Scan injects actual files + size + header, no generic placeholder" ;;
    "common.file-naming-rules") content="# Common File Naming Rules - Optimal - FILE.NAMING.RULES.MD
Dot naming aistd.*.md lowercase no spaces category.file.md, templates *.template.md, steps stepX.php, required 01.requirements.md etc. No camelCase no spaces dots for categories dashes for subcategories common.file-naming-rules.md" ;;
    "common.coding-standards") content="# Common Coding Standards - Optimal - CODINGSTANDARDS.MD
PHP paths.php chain 6 levels no hardcoded APP_ROOT BASE_ROOT APP_URL from .env, UI BS5 5.3.3 fontawesome 6.5 responsive col-md-3 sidebar col-md-9 content sticky-top navbar d-flex flex-md-row sidebar flex-shrink-0 260px sticky top 56px, JS bootstrap.bundle.min.js data-bs-toggle tab working data-bs-toggle collapse accordion Expand All/Collapse All, CSS overflow-wrap break-word word-break break-word white-space pre-wrap for pre wrapping within content window, breadcrumbs clickable, perms chmod 644 php 777 data/ docs/ chown \$(whoami):staff xattr -cr" ;;
    "common.data-model") content="# Common Data Model - Optimal - DATA-MODEL + DATABASEDESIGN
wizard.json {step1:{completed,data:{project_name,project_path}}, step2:{completed data:{goals_primary}}... step10} flattened + defaults.json + .env → build, docs.manifest.json {requirements:{files:[],scan:[]}, wizard:{}, frontend:{scan:[frontend templates]}, admin:{scan:[admin]}, backend:{scan:[includes php config]}, auth:{scan:[php]}, common:{scan:[docs]}}, form_fields.json {required:[project_name project_path] optional:[goals_primary constraints stakeholders deliverables risks questions]}, data/build/*.md and docs/aistd/aistd.*.md each header + true scan" ;;
    "common.security") content="# Common Security - Optimal - SECURITY.MD
Auth is_logged_in() bootstrap redirect login if !logged current_user(), perms files owned by rbutareOld vs rbutare causes Permission denied Operation not permitted on chmod fix sudo chown -R \$(whoami):staff chmod 644 php 777 data docs xattr -cr removes @ quarantine that blocks include even with 777, no hardcoded secrets in .env.example, tools files.perm.sh checks perms files.missing.sh checks missing test.all.sh -m circular menu" ;;
    "common.testing") content="# Common Testing - Optimal - TESTING.MD
sh standards take arguments -m menu circular so user can run individual options test dir test apps test all etc, tools/files.missing.sh checks missing per required list + manifest exit missing count, tools/files.perm.sh checks directory missing perms one test for all arg --fix chmod, tools/test.all.sh test dir test apps test all + summary what worked/not PASS/FAIL count + what worked vs what not + audit + fix perms + fix owner + circular menu -m 1)dir 2)apps 3)all 4)audit 5)fix perms 6)show owner 7)exit loops, Admin → Test tab runs 12 checks wizard.json exists/readable build writable aistd writable manifest form_fields faq guide navbar syntax content-start syntax build.php exists no hardcoded paths → table PASS/FAIL + summary X/Y PASS FAIL" ;;
    "common.deployment") content="# Common Deployment - Optimal - DEPLOYMENT.MD
Install true docs: unzip ~/Downloads/aistd-true-docs.zip -d APP_ROOT/ && chmod -R 777 data/ docs/ && xattr -cr APP_ROOT/ && sudo chown -R \$(whoami):staff APP_ROOT/, terminal commands needed TBA future handle directly from UX: sudo chown -R \$(whoami):staff, chmod -R 755 pages/ templates/, chmod -R 777 data/ docs/, xattr -cr, php php/build.php or via UI Build button, system env /Users/rbutare/websites/system/.env editable Admin→System tab, app env APP_ROOT/.env editable CRUD, check ls -l@ pages/steps/step10.php, ls -ld data/ docs/ docs/aistd/ data/build/" ;;
    "common.web-access-architecture") content="# Common Web Access Architecture - Optimal - WEB-ACCESS-ARCHITECTURE
BASE_ROOT=/Users/rbutare/websites BASE_URL=http://rickweb APP_URL=http://rickweb/apps/{{project_name}} System /Users/rbutare/websites/system/php/paths.php defines BASE_ROOT BASE_URL loads .env App APP_ROOT=/Users/rbutare/websites/apps/{{project_name}} APP_URL via BASE_URL + /apps/{{project_name}} Apache _www user needs read owner rbutareOld vs rbutare causes Permission denied even with 777 if @ xattr present fix xattr -cr Router aiwizard.index.php?section=wizard|docs|admin|help with breadcrumbs clickable helps user from getting lost tabs help complex comparisons" ;;
  esac
  echo "$content" > "$ROOT/docs/optimal/$name.md"
  echo "Created optimal/$name.md"
done

# Copy to aistd with header
for f in "$ROOT/docs/required/"*.md "$ROOT/docs/optimal/"*.md; do
  bn=$(basename "$f")
  cp "$f" "$ROOT/docs/aistd/aistd.$bn"
done

echo "Counts: required=$(ls "$ROOT/docs/required/" | wc -l) optimal=$(ls "$ROOT/docs/optimal/" | wc -l) aistd=$(ls "$ROOT/docs/aistd/" | wc -l)"
chmod -R 777 "$ROOT/docs/" "$ROOT/data/"
chown -R $(whoami):staff "$ROOT/docs/" "$ROOT/data/" 2>/dev/null || sudo chown -R $(whoami):staff "$ROOT/docs/" "$ROOT/data/"
echo "Done"
