#!/usr/bin/env bash
#
# install_docs_structure.sh
#
# Creates the project documentation structure and starter MD files.
# Safe to run repeatedly: existing files are NOT overwritten.
#
# Usage:
#   ./install_docs_structure.sh [PROJECT_ROOT]
#
# Default:
#   PROJECT_ROOT=.
#

set -euo pipefail

PROJECT_ROOT="${1:-.}"
DOCS_DIR="${PROJECT_ROOT%/}/docs"

echo "Creating documentation structure under: ${DOCS_DIR}"

mkdir -p \
  "$DOCS_DIR/ai" \
  "$DOCS_DIR/architecture" \
  "$DOCS_DIR/standards" \
  "$DOCS_DIR/ui" \
  "$DOCS_DIR/development" \
  "$DOCS_DIR/data" \
  "$DOCS_DIR/requirements" \
  "$DOCS_DIR/reference" \
  "$DOCS_DIR/examples"

create_file() {
  local file="$1"
  if [[ -e "$file" ]]; then
    echo "SKIP  $file"
  else
    cat > "$file"
    echo "CREATE $file"
  fi
}

create_file "$DOCS_DIR/README.md" <<'EOF'
# Project Documentation

## Purpose

Central index for project requirements, architecture, standards, development rules,
AI instructions, data standards, UI standards, and system requirements.

## Documentation Authority

When documents conflict, use this priority:

1. Security requirements
2. System architecture
3. Project requirements
4. Coding standards
5. Language-specific standards
6. UI standards
7. Data standards
8. Examples/reference material
9. Existing implementation

Examples are not requirements unless explicitly identified as such.

## Structure

- `ai/` — instructions and context for AI coding agents
- `architecture/` — how the system is organized
- `standards/` — coding and naming rules
- `ui/` — Bootstrap, accessibility, themes, UX
- `development/` — errors, logging, security, testing, review
- `data/` — JSON, database, validation rules
- `requirements/` — system-level requirements
- `reference/` — source/reference material
- `examples/` — examples that are not authoritative requirements

## Status

This documentation set is being established from the existing consolidated MD
source. Questions, recommendations, and missing information are intentionally
tracked in each document until resolved.
EOF

create_file "$DOCS_DIR/ai/ai_context.md" <<'EOF'
# AI Context

## Purpose

Provide the minimum authoritative project context required by an AI coding agent.

## Project

- Project name:
- Project purpose:
- Primary technology:
- Deployment environment:
- Current phase:

## Technology

- PHP:
- JavaScript:
- HTML:
- CSS:
- Bootstrap:
- MySQL:
- Bash:
- JSON:

## Architectural Rules

See:
- `../architecture/system_architecture.md`
- `../architecture/directory_structure.md`
- `../architecture/paths_and_environment.md`
- `../architecture/shared_components.md`

## Coding Rules

See:
- `../standards/coding_standards.md`
- `../standards/naming_standards.md`
- language-specific standards

## AI Rules

See `ai_instructions.md`.

## Open Questions

- What is the final application/system name?
- Which requirements are global versus application-specific?
- Which existing code is authoritative?
EOF

create_file "$DOCS_DIR/ai/ai_instructions.md" <<'EOF'
# AI Instructions

## Purpose

Define how AI coding agents must interpret and modify this project.

## Authority

When documents conflict:

1. Security requirements
2. Architecture
3. Requirements
4. Coding standards
5. Language-specific standards
6. UI/data standards
7. Examples
8. Existing implementation

Documentation requirements override example code.

## Required Behavior

- Read relevant documentation before modifying code.
- Do not invent requirements.
- Do not silently resolve documented conflicts.
- Identify ambiguity under `Q - Questions`.
- Record proposed solutions under `R - Recommendations`.
- Record undocumented requirements under `M - Missing`.
- Prefer reusable shared components.
- Do not duplicate shared functionality.
- Do not hardcode application paths.
- Preserve backward compatibility unless a breaking change is explicitly approved.
- Update documentation when behavior or architecture changes.

## Before Coding

- Identify affected requirements.
- Identify affected architecture.
- Identify shared components that can be reused.
- Identify security implications.
- Identify tests required.

## After Coding

- Validate functionality.
- Run appropriate tests.
- Review error handling.
- Review security.
- Update documentation.
EOF

create_file "$DOCS_DIR/ai/ai_workflow.md" <<'EOF'
# AI Development Workflow

## Workflow

1. Read `ai_context.md`.
2. Read applicable requirements.
3. Read applicable architecture documents.
4. Read applicable standards.
5. Identify Q/R/M items.
6. Plan the change.
7. Implement using shared components.
8. Test.
9. Perform security/error-handling review.
10. Update documentation.
11. Summarize changes and unresolved questions.

## Change Classification

- Bug fix
- Enhancement
- Refactor
- Architecture change
- Security change
- Documentation change
EOF

create_file "$DOCS_DIR/architecture/system_architecture.md" <<'EOF'
# System Architecture

## Purpose

Define how the application and shared system services fit together.

## Layers

- Presentation:
- UI:
- JavaScript:
- PHP/application:
- API:
- Data:
- System/shared services:

## Shared Services

Potential services identified from the source:

- `sys.paths`
- `sys.load.env`
- `sys.debug`
- `sys.themes`
- `sys.local`
- `sys.dir.listing`
- `sys.viewer`
- `sys.admin`
- `sys.test`
- `sys.admin.reports`

## Q - Questions

- Is `sys.*` a formal shared framework or only a proposed collection of utilities?
- Which applications consume the system services?
- Are services PHP-only, shell-only, JavaScript-capable, or multi-language?
- Is MySQL part of the base system or optional per application?

## R - Recommendations

- Define a formal service boundary for `sys.*`.
- Give each service a documented public interface.
- Keep application-specific code separate from system services.

## M - Missing

- Architecture diagram
- Dependency rules
- Service lifecycle
- API contracts
- Authentication/authorization model
- Deployment architecture
EOF

create_file "$DOCS_DIR/architecture/directory_structure.md" <<'EOF'
# Directory Structure

## Purpose

Define the authoritative project directory tree.

## Rules

- No undocumented application directories.
- Shared code has one authoritative location.
- Paths must not be duplicated across applications.
- Documentation locations are standardized.

## Q - Questions

- What is the authoritative project root?
- Is `docs/` always located at project root?
- Where do shared PHP, JS, CSS, shell, and configuration files live?
- Are multiple applications intentionally housed under one tree?

## R - Recommendations

- Establish one canonical project tree.
- Document generated, temporary, cache, backup, and deployment directories.

## M - Missing

- Complete directory tree
- Ownership/permissions rules
- Runtime vs source directories
- Temporary/cache rules
- Backup location
EOF

create_file "$DOCS_DIR/architecture/paths_and_environment.md" <<'EOF'
# Paths and Environment

## Purpose

Define how applications resolve paths and environment configuration.

## Current Rule

The source states that absolute paths should be handled through `paths.php`,
while existing PHP examples use `__DIR__`.

## Q - Questions

- Is `sys.paths.php` mandatory for all PHP applications?
- Is `__DIR__` allowed outside the path service?
- What are the canonical environment variables?
- Where is `.env` located?
- Is `.env` used in production?

## R - Recommendations

- Centralize application paths.
- Permit `__DIR__` only inside the centralized path implementation if desired.
- Provide `.env.example`.
- Fail clearly when required environment variables are missing.

## M - Missing

- Path variable catalog
- `.env` specification
- Environment precedence
- Development/production rules
- Secret handling
- Validation behavior
EOF

create_file "$DOCS_DIR/architecture/configuration.md" <<'EOF'
# Configuration

## Purpose

Define configuration sources, precedence, validation, and secrets.

## Q - Questions

- `.env`, environment variables, PHP config files, or all three?
- Which values are required?
- Which values may be overridden?
- How are secrets managed?

## R - Recommendations

- Keep secrets out of source control.
- Maintain `.env.example`.
- Validate required configuration at startup.

## M - Missing

- Configuration schema
- Required variable list
- Precedence rules
- Production secret strategy
- Configuration validation requirements
EOF

create_file "$DOCS_DIR/architecture/shared_components.md" <<'EOF'
# Shared Components

## Purpose

Define reusable system/application components and prevent duplicate implementations.

## Identified Components

- Toast/message system
- Spinner/page loader
- Modal helper
- Debug/logging utility
- Theme manager
- Path service
- Environment loader
- Viewer
- Admin utilities

## Q - Questions

- Which components are mandatory for every application?
- What is the canonical file/location for each component?
- Are components versioned independently?
- What is the public API for each component?

## R - Recommendations

For each shared component document:

- Purpose
- Location
- Public API
- Inputs/outputs
- Dependencies
- Error behavior
- Testing
- Example usage

## M - Missing

- Component inventory
- API definitions
- Dependency map
- Versioning strategy
EOF

create_file "$DOCS_DIR/standards/coding_standards.md" <<'EOF'
# Coding Standards

## Purpose

Global coding rules applicable to all project code.

## Core Principles

- DRY
- KISS
- Secure by default
- Reusable components
- Separation of concerns
- No hardcoded paths
- No unnecessary duplication

## Language Standards

| Language | Standard |
|---|---|
| PHP | PSR-12 |
| JavaScript | ES6+ |
| HTML | HTML5 |
| CSS | Project CSS standards |
| Bash | Bash standards |
| SQL | SQL standards |
| JSON | JSON standards |
| Markdown | Markdown standards |

## Q - Questions

- Is jQuery still an approved dependency?
- Is ES6 module syntax mandatory everywhere?
- What PHP version is required?
- What JavaScript/browser baseline is required?

## R - Recommendations

Keep this document global and move language-specific details into dedicated files.

## M - Missing

- Supported PHP version
- Supported browser versions
- Dependency policy
- Build/package management rules
EOF

create_file "$DOCS_DIR/standards/naming_standards.md" <<'EOF'
# Naming Standards

## Purpose

Define naming conventions by artifact type.

## Proposed Defaults

| Artifact | Convention |
|---|---|
| Files | `snake_case` |
| Folders | `snake_case` |
| PHP functions | `camelCase` or project-selected convention |
| JS functions | `camelCase` |
| JS variables | `camelCase` |
| CSS classes | `kebab-case` |
| JSON properties | Project-selected convention |
| Database tables | `snake_case` |
| Database columns | `snake_case` |
| Classes | `PascalCase` |

## Q - Questions

- Should PHP functions be `camelCase` or `snake_case`?
- Should JSON keys use camelCase or snake_case?
- Should all filenames, including HTML/CSS/JS, be snake_case?
- Are acronyms normalized?

## R - Recommendations

Choose one convention per artifact and prohibit exceptions unless documented.

## M - Missing

- Complete naming matrix
- Acronym rules
- Boolean naming rules
- Constant naming rules
- API endpoint naming
EOF

create_file "$DOCS_DIR/standards/php_standards.md" <<'EOF'
# PHP Standards

## Rules

- PSR-12
- Use strict types where practical
- Avoid hardcoded paths
- Centralize environment/configuration loading
- Validate input
- Escape output
- Handle errors explicitly

## Q - Questions

- Is `declare(strict_types=1)` mandatory?
- What PHP version is supported?
- Which framework/libraries are allowed?

## R - Recommendations

Make strict typing mandatory for new PHP files unless a documented compatibility reason exists.

## M - Missing

- PHP version
- Dependency policy
- Exception/error policy
- API response standard
- Security standard reference
EOF

create_file "$DOCS_DIR/standards/javascript_standards.md" <<'EOF'
# JavaScript Standards

## Rules

- Prefer ES6 modules.
- Avoid duplicated shared utilities.
- Use shared UI utilities.
- Use clear camelCase names.
- Keep inline styles out of JavaScript/HTML.
- Async operations must provide appropriate loading/error feedback.
- Prefer modern browser APIs unless an approved dependency requires otherwise.

## Q - Questions

- Is jQuery allowed?
- Is `fetch()` the standard API?
- Are all scripts required to be modules?
- What browser baseline is supported?

## R - Recommendations

Use ES modules + `fetch()` + Bootstrap 5 APIs for new development unless legacy compatibility requires jQuery.

## M - Missing

- JS module structure
- Dependency rules
- API/AJAX standard
- Promise/async error standard
EOF

create_file "$DOCS_DIR/standards/bash_standards.md" <<'EOF'
# Bash Standards

## Rules

- Use `set -euo pipefail` where appropriate.
- Quote variables.
- Load configuration consistently.
- Prefer idempotent scripts.
- Provide clear errors.
- Do not hardcode environment-specific paths.

## Q - Questions

- Is `.env` loaded by every script?
- What Bash version is required?
- Are scripts expected to run under `/bin/sh` or Bash?

## R - Recommendations

Use Bash explicitly for scripts requiring Bash features and `#!/usr/bin/env bash`.

## M - Missing

- Shell compatibility
- Exit code standard
- Logging standard
- Dry-run convention
- Destructive-operation safeguards
EOF

create_file "$DOCS_DIR/standards/html_css_standards.md" <<'EOF'
# HTML and CSS Standards

## Rules

- Semantic HTML5
- Responsive layout
- Accessible labels and controls
- Bootstrap 5
- No unnecessary inline styles
- CSS classes use project naming conventions

## Q - Questions

- Is Bootstrap mandatory for every UI?
- Is custom CSS allowed?
- What CSS naming methodology is preferred?

## R - Recommendations

Use Bootstrap 5 for layout/components and project CSS for application-specific presentation.

## M - Missing

- CSS architecture
- Breakpoint policy
- Accessibility requirements
- Component styling rules
EOF

create_file "$DOCS_DIR/standards/sql_standards.md" <<'EOF'
# SQL Standards

## Rules

- Lowercase database identifiers.
- Explicit keys.
- Document schema changes.
- Validate/parameterize external input.

## Q - Questions

- Is MySQL the only supported database?
- What MySQL/MariaDB version?
- Migration tool or manual SQL?
- Naming rules for indexes/foreign keys?

## R - Recommendations

Use migrations for schema changes and parameterized queries for application SQL.

## M - Missing

- Schema migration standard
- Index naming
- Foreign key naming
- Transaction rules
- Backup/restore requirements
EOF

create_file "$DOCS_DIR/standards/markdown_standards.md" <<'EOF'
# Markdown Standards

## Purpose

Define how project documentation is structured.

## Recommended Structure

Use only sections relevant to the document:

- Purpose
- Scope
- Requirements
- Rules
- Q - Questions
- R - Recommendations
- M - Missing
- Examples
- Related Documents
- Change History

## Q - Questions

- Is a standard metadata header required?
- Should every document have status/owner/version?

## R - Recommendations

Do not force every document to contain a summary table. Use a consistent structure while allowing document-specific sections.

## M - Missing

- Document metadata standard
- Versioning convention
- Change history format
- Cross-reference rules
EOF

create_file "$DOCS_DIR/ui/ui_standards.md" <<'EOF'
# UI Standards

## Purpose

Define common UX behavior across applications.

## Identified Requirements

- Bootstrap 5
- Responsive UI
- Consistent navigation
- Toasts/messages
- Spinners/page loaders
- Modals
- Themes
- Debug/admin controls where appropriate

## Q - Questions

- Which UI components are mandatory?
- Should all applications use the same navigation pattern?
- Are themes global or application-specific?

## R - Recommendations

Define reusable UI components and document their behavior once.

## M - Missing

- UI component catalog
- UX rules
- Loading behavior
- Empty-state behavior
- Confirmation behavior
EOF

create_file "$DOCS_DIR/ui/bootstrap_standards.md" <<'EOF'
# Bootstrap Standards

## Standard

Bootstrap 5 is the preferred UI framework.

## Q - Questions

- Exact Bootstrap version?
- CDN or local assets?
- Is Bootswatch approved?
- Are Bootstrap JavaScript APIs mandatory?

## R - Recommendations

Pin the Bootstrap version and avoid changing CDN versions independently in individual pages.

## M - Missing

- Version
- Asset strategy
- Customization strategy
- Component usage rules
EOF

create_file "$DOCS_DIR/ui/accessibility.md" <<'EOF'
# Accessibility

## Purpose

Define accessibility requirements for all user interfaces.

## Q - Questions

- What accessibility target is required?
- Is WCAG 2.1/2.2 AA the target?
- Are automated accessibility tests required?

## R - Recommendations

Use semantic HTML, labels, keyboard navigation, visible focus, meaningful error messages, and appropriate ARIA only when necessary.

## M - Missing

- Accessibility target
- Testing requirements
- Keyboard-navigation standard
- Screen-reader testing
EOF

create_file "$DOCS_DIR/ui/themes.md" <<'EOF'
# Themes

## Identified Behavior

The source includes runtime Bootstrap/Bootswatch theme selection.

## Q - Questions

- Are themes persisted?
- Where is the preference stored?
- Which themes are supported?
- Is dark mode required?
- Is theme switching global?

## R - Recommendations

Centralize theme management in `sys.themes` and persist user preference through the approved local/preferences service.

## M - Missing

- Theme catalog
- Persistence mechanism
- Default theme
- Accessibility requirements
- Theme API
EOF

create_file "$DOCS_DIR/development/error_handling.md" <<'EOF'
# Error Handling

## Principle

User feedback and developer diagnostics are separate concerns.

## Proposed Model

| Situation | User Response | Developer Response |
|---|---|---|
| Success | Toast | Optional debug |
| Validation | Inline message/toast | Debug if useful |
| Recoverable error | Alert/message | Log |
| Fatal error | Error page/panel | Log |
| Security event | Generic message | Security log |

## Q - Questions

- What constitutes a fatal error?
- Which errors are logged?
- Where are logs stored?
- Should users see error IDs?

## R - Recommendations

Do not require every error to be a toast. Use the UI response appropriate to severity.

## M - Missing

- Error taxonomy
- HTTP/API error format
- Error codes
- Production error behavior
- Log correlation IDs
EOF

create_file "$DOCS_DIR/development/logging_and_debugging.md" <<'EOF'
# Logging and Debugging

## Identified Features

- Debug enable/disable
- Debug levels
- Browser console diagnostics
- `sys.debug`
- Logs

## Q - Questions

- What are the debug levels?
- What are the production logging rules?
- Where do PHP/Bash/JS logs go?
- How long are logs retained?

## R - Recommendations

Separate debug output from persistent application logging.

## M - Missing

- Log levels
- Log format
- Log locations
- Retention/rotation
- Production policy
- Sensitive-data redaction
EOF

create_file "$DOCS_DIR/development/security_standards.md" <<'EOF'
# Security Standards

## Required Areas

- Input validation
- Output escaping
- XSS prevention
- CSRF protection
- Authentication
- Authorization
- Secure file operations
- Path traversal prevention
- URL validation
- Secret handling
- Error disclosure
- Secure backups/restores

## Q - Questions

- Is authentication required for admin functions?
- Who may edit/restore JSON?
- Are API endpoints protected?
- What security baseline is required?

## R - Recommendations

Treat all browser/API input as untrusted. Never expose internal filesystem paths or stack traces in production.

## M - Missing

- Authentication model
- Authorization model
- Session policy
- CSRF strategy
- Security headers
- Content Security Policy
- Audit logging
EOF

create_file "$DOCS_DIR/development/testing_standards.md" <<'EOF'
# Testing Standards

## Test Types

- Unit
- Integration
- API
- UI
- Regression
- Security
- Smoke
- System validation

## Q - Questions

- Which test framework(s)?
- What is the minimum required coverage?
- What tests must pass before deployment?
- Is `sys.test.manifest` authoritative?

## R - Recommendations

Every shared component should have tests appropriate to its behavior.

## M - Missing

- Test framework
- Test directory
- CI process
- Coverage target
- Browser test strategy
- Test data strategy
EOF

create_file "$DOCS_DIR/development/code_review.md" <<'EOF'
# Code Review

## Checklist

- [ ] Correctness
- [ ] Requirements satisfied
- [ ] Edge cases handled
- [ ] Security reviewed
- [ ] Performance reviewed
- [ ] Shared components reused
- [ ] No unnecessary duplication
- [ ] Error handling reviewed
- [ ] Logging reviewed
- [ ] Tests added/updated
- [ ] Documentation updated

## Q - Questions

- Who approves changes?
- Is AI-generated code always reviewed by a human?
- What requires a second reviewer?

## R - Recommendations

Use this as the common review checklist across PHP, Bash, JS, SQL, HTML, and CSS.

## M - Missing

- Approval policy
- Branch/PR policy
- Required automated checks
- Release criteria
EOF

create_file "$DOCS_DIR/development/backup_and_restore.md" <<'EOF'
# Backup and Restore

## Identified Requirements

The source includes JSON backup and restore behavior.

## Q - Questions

- When is a backup created?
- How many backups are retained?
- Where are backups stored?
- Who may restore?
- Is restore atomic?
- Can restore be rolled back?

## R - Recommendations

Always create a backup before destructive restore operations and validate backup contents before replacing active data.

## M - Missing

- Naming convention
- Retention policy
- Permissions
- Integrity validation
- Audit trail
- Rollback behavior
EOF

create_file "$DOCS_DIR/data/json_standards.md" <<'EOF'
# JSON Standards

## Identified Fields

The source uses fields including:

- `id`
- `title`
- `url`
- `category`
- `subCategory`
- `comment`
- `priority`
- `status`
- `created`
- `modified`

## Q - Questions

- Is `subCategory` or `subCat` authoritative?
- Is `priority` separate from `status`?
- What fields are required?
- What date format is used?
- Is the top-level JSON an array or versioned object?

## R - Recommendations

Separate `priority` and `status`. Use one canonical field name and one canonical date format.

## M - Missing

- Formal schema
- Required/optional fields
- Allowed values
- Date format
- Versioning
- Migration rules
- Validation rules
EOF

create_file "$DOCS_DIR/data/database_standards.md" <<'EOF'
# Database Standards

## Status

The current source states that database support is not yet required.

## Q - Questions

- Is MySQL planned for the base system?
- Which applications require it?
- What schema migration strategy will be used?

## R - Recommendations

Keep database-specific rules separate from the JSON/file-based applications until a database architecture is approved.

## M - Missing

- Database architecture
- Connection/configuration standard
- Schema rules
- Migration rules
- Backup policy
EOF

create_file "$DOCS_DIR/data/data_validation.md" <<'EOF'
# Data Validation

## Scope

Define validation for JSON, API input, forms, files, URLs, dates, IDs, categories, status, and priority.

## Q - Questions

- Where is validation performed?
- Client-side, server-side, or both?
- Is JSON Schema used?

## R - Recommendations

Server-side validation is authoritative. Client-side validation is for user experience.

## M - Missing

- Validation rules
- JSON schema
- URL rules
- Date rules
- Error response format
EOF

create_file "$DOCS_DIR/requirements/system_tools.md" <<'EOF'
# System Tools Requirements

## Identified Tools

- `sys.debug`
- `sys.themes`
- `sys.local`
- `sys.dir.listing`
- `sys.md.viewer.php`
- `sys.md.viewer.sh`
- `sys.json.viewer.php`
- `sys.json.viewer.sh`
- `sys.viewer`
- `sys.paths.php`
- `sys.paths.sh`
- `sys.load.env.php`
- `sys.load.env.js`
- `sys.load.env.sh`
- `sys.load.env.py`
- `sys.admin.test`
- `sys.admin.audit`
- `sys.admin.navbar.php`
- `sys.admin.sidebar.php`
- `sys.test.manifest`
- `sys.admin.reports`

## Q - Questions

- Which tools are approved?
- Which are proposals?
- Which are already implemented?
- Which are shared across projects?
- Should one `sys.viewer` replace separate viewers?

## R - Recommendations

Create one requirements entry per system service with:
purpose, inputs, outputs, dependencies, security, errors, tests, and status.

## M - Missing

- Status per tool
- Interface/API
- Dependencies
- Security
- Test requirements
- Ownership
EOF

create_file "$DOCS_DIR/requirements/system_viewer.md" <<'EOF'
# System Viewer Requirements

## Purpose

Define a common viewer for Markdown, JSON, and potentially other text/file types.

## Identified Concepts

- Markdown viewer
- JSON viewer
- Unified `sys.viewer`

## Q - Questions

- Should one viewer support multiple file types?
- Which file types are allowed?
- Can users edit files?
- Is syntax highlighting required?
- How are large files handled?

## R - Recommendations

Use one viewer architecture with type-specific renderers where practical.

## M - Missing

- UI requirements
- Security model
- File access rules
- Supported formats
- Search/filter behavior
EOF

create_file "$DOCS_DIR/requirements/system_admin.md" <<'EOF'
# System Administration Requirements

## Identified Concepts

- `sys.admin.test`
- `sys.admin.audit`
- `sys.admin.navbar.php`
- `sys.admin.sidebar.php`
- `sys.admin.reports`

## Q - Questions

- What administrator role(s) exist?
- What functions require authentication?
- What is included in audit?
- Which reports are required?

## R - Recommendations

Treat administration as a protected system area with audit logging.

## M - Missing

- Roles
- Permissions
- Audit events
- Admin UI
- Reports
- Security requirements
EOF

create_file "$DOCS_DIR/requirements/system_testing.md" <<'EOF'
# System Testing Requirements

## Identified Concepts

- System tests
- Validation of missing directories
- Permissions
- Owners
- Naming
- Hardcoded paths
- Non-standard items
- `sys.test.manifest`

## Q - Questions

- What constitutes a failure?
- Should tests repair issues or report only?
- Which checks are mandatory?

## R - Recommendations

Make system validation read-only by default, with explicit repair operations.

## M - Missing

- Test catalog
- Exit codes
- Report format
- Repair policy
- Permission/ownership policy
EOF

create_file "$DOCS_DIR/requirements/system_reports.md" <<'EOF'
# System Reports Requirements

## Purpose

Define key administrative/system reports.

## Q - Questions

- Which reports are required?
- Who can run them?
- HTML, JSON, CSV, or all three?
- Are reports stored or generated on demand?

## R - Recommendations

Support machine-readable JSON plus human-readable HTML where practical.

## M - Missing

- Report catalog
- Data sources
- Formats
- Permissions
- Retention
EOF

create_file "$DOCS_DIR/reference/source_consolidated_review.md" <<'EOF'
# Source Consolidated Review

## Purpose

This file is a reference record for the original consolidated Markdown source that
contained standards, application code, JSON, TODO items, and proposed system tools.

## Important Finding

The original source mixes:

- Coding standards
- Code of conduct
- Code review
- HTML/JS/PHP implementation
- JSON data
- TODOs
- System service proposals

These categories should not remain authoritative in one file.

## Q - Questions

- Which embedded implementation is current?
- Which examples are obsolete?
- Which TODO items are requirements versus experiments?

## R - Recommendations

Keep source material only as reference. Promote approved requirements into the
appropriate authoritative documents.

## M - Missing

- Decision log
- Requirement IDs
- Source-to-requirement traceability
EOF

cat <<EOF

Documentation structure created.

Next recommended sequence:
  1. ai/ai_context.md
  2. ai/ai_instructions.md
  3. architecture/system_architecture.md
  4. architecture/directory_structure.md
  5. architecture/paths_and_environment.md
  6. architecture/shared_components.md
  7. standards/naming_standards.md
  8. development/security_standards.md
  9. development/error_handling.md
 10. data/json_standards.md
 11. requirements/system_tools.md

Existing files were not overwritten.
EOF
