#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

PROGRAM_NAME="${0##*/}"
FORCE=0
DRY_RUN=0
YES=0
APPS=("games/tictoe" "games/snake" "fid" "tips")

usage() {
    cat <<USAGE
Usage: ${PROGRAM_NAME} [options]

Creates the agreed base-level PHP project documentation structure in the
current directory. Existing files are never replaced unless --force is used.

Options:
  --dry_run       Show planned changes without writing files
  --force         Replace managed documentation files
  --yes           Do not request confirmation
  --app PATH      Add an application path below apps/ (repeatable)
  --no_default_apps  Do not create games/tictoe, games/snake, fid, and tips
  --help          Show this help

Examples:
  ./${PROGRAM_NAME} --dry_run
  ./${PROGRAM_NAME}
  ./${PROGRAM_NAME} --app games/puzzle --app reports
USAGE
}

DEFAULT_APPS=1
CUSTOM_APPS=()
while [ "$#" -gt 0 ]; do
    case "$1" in
        --dry_run) DRY_RUN=1 ;;
        --force) FORCE=1 ;;
        --yes) YES=1 ;;
        --no_default_apps) DEFAULT_APPS=0 ;;
        --app)
            shift
            [ "$#" -gt 0 ] || { printf 'ERROR: --app requires a path.\n' >&2; exit 2; }
            CUSTOM_APPS+=("$1")
            ;;
        --help) usage; exit 0 ;;
        *) printf 'ERROR: Unknown option: %s\n' "$1" >&2; usage >&2; exit 2 ;;
    esac
    shift
done

validate_name() {
    case "$1" in
        ""|/*|*".."*|*" "*|*"-"*|*"~"*|*[!a-z0-9_/]*)
            printf 'ERROR: Invalid application path: %s\n' "$1" >&2
            printf 'Use lowercase letters, numbers, underscores, and slashes only.\n' >&2
            exit 2
            ;;
    esac
}

for app in "${CUSTOM_APPS[@]}"; do validate_name "$app"; done
if [ "$DEFAULT_APPS" -eq 0 ]; then APPS=(); fi
APPS+=("${CUSTOM_APPS[@]}")

write_file() {
    target="$1"
    content="$2"
    if [ -e "$target" ] && [ "$FORCE" -ne 1 ]; then
        printf 'SKIP existing file: %s\n' "$target"
        return
    fi
    if [ "$DRY_RUN" -eq 1 ]; then
        printf 'WRITE %s\n' "$target"
        return
    fi
    mkdir -p "$(dirname "$target")"
    printf '%s\n' "$content" > "$target"
    printf 'WROTE %s\n' "$target"
}

make_dir() {
    if [ "$DRY_RUN" -eq 1 ]; then
        printf 'MKDIR %s\n' "$1"
    else
        mkdir -p "$1"
    fi
}

printf 'Project root: %s\n' "$(pwd)"
printf 'Applications: %s\n' "${APPS[*]:-none}"
if [ "$YES" -ne 1 ] && [ "$DRY_RUN" -ne 1 ]; then
    printf 'Create the base documentation structure here? [y/N] '
    read -r reply
    case "$reply" in y|Y|yes|YES) ;; *) printf 'No changes made.\n'; exit 0 ;; esac
fi

for dir in \
    system/{php,css,js,core,config,data/{logs,config,fonts,sql},images,scripts,docs} \
    docs scripts; do
    make_dir "$dir"
done

write_file '.gitignore' '# Local configuration, secrets, runtime data, and generated files
.env
.env.*
!.env.example
*.log
system/data/logs/
apps/*/data/logs/
.DS_Store
'

write_file '.env.example' '# Global path defaults. Copy to .env and set real local values.
# Do not commit .env files, credentials, API keys, passwords, or licenses.
PROJECT_ROOT=
SYSTEM_ROOT=
APPS_ROOT=
SYSTEM_DATA_ROOT=
SYSTEM_LOG_ROOT=
'

write_file 'README.md' '# Project Root

This repository is a PHP-based multi-application platform with two levels:

- `system/` contains shared system code, configuration, resources, standards, and global documentation.
- `apps/` contains individual applications. Each application may add or override documented system behavior only for that application.

## Read First

- [AI agent rules](AGENTS.md)
- [System documentation](system/docs/README.md)
- [Documentation standard](system/docs/documentation_standard.md)
- [Configuration rules](system/docs/configuration.md)
- [Git workflow](system/docs/git_workflow.md)

## Configuration

The global `.env` defines shared paths and defaults. Each application may have an `apps/<app_name>/.env` file to override only values required by that application, such as API, database, password, or license configuration.

Do not commit `.env` files. Commit only `.env.example` files.
'

write_file 'AGENTS.md' '# AI Agent Rules

## Mandatory Reading Order

Before inspecting or changing code, read:

1. This `AGENTS.md` file.
2. `system/docs/README.md`.
3. The relevant global document under `system/docs/`.
4. The nearest application `AGENTS.md` when working under `apps/`.
5. Relevant documentation in `apps/<app_name>/docs/`.

Application rules may add requirements but must not weaken these rules.

## Architecture

- `system/` is the shared global system layer.
- `apps/` contains individual applications.
- Global definitions live in `system/docs/`.
- Application documents in `apps/<app_name>/docs/` add or explicitly override system behavior for that application only.
- Global `.env` settings provide shared paths and defaults.
- Application `.env` settings override only that application configuration.

## File Naming

- Do not use hyphens in project-created filenames or directory names.
- Use lowercase `snake_case` for project-created names.
- Do not use spaces, tildes, or special characters.
- Preserve required ecosystem names exactly: `.env`, `.gitignore`, `README.md`, `AGENTS.md`, `LICENSE.md`, `SECURITY.md`, and `.github`.

## Approved Technology Scope

- Bash for macOS and Linux automation.
- PHP for server-side code.
- HTML, JavaScript, Bootstrap 5, Font Awesome, and DataTables for UI work.
- MySQL for data storage.
- AWK or Python only when they are appropriate for the task.
- Do not introduce Node.js, npm, Composer, Docker, frameworks, packages, or external dependencies without explicit approval.

## Code Quality

- Produce production-quality code.
- Use modular, structured programming; do not introduce object-oriented architecture by default.
- Limit objects to cases where they provide clear value, including MySQL/PDO access.
- Separate configuration, data access, business logic, output, and UI behavior.
- Validate all input and handle errors for every filesystem, database, command, network, and API operation.
- Do not expose secrets or internal diagnostics to end users.

## Required Change Process

- Do not assume unclear requirements; ask for clarification.
- Ask for confirmation before destructive changes, data changes, deployment, sending external requests, adding dependencies, or changing security behavior.
- Inspect relevant code and documentation before changes.
- Update applicable global or application documentation with each change.
- Run applicable syntax checks and tests before delivery, including relevant error paths.
- Report exactly what was tested. If testing cannot be performed, state why and identify the unverified risk.

## Git

- The designated master repository is the canonical single source of truth.
- Do not synchronize repositories by manually copying source files.
- Check `git status` before and after changes.
- Do not commit `.env`, logs, caches, generated files, credentials, or secrets.
'

write_file 'CONTRIBUTING.md' '# Contributing

Read `AGENTS.md` and the relevant documents in `system/docs/` before making changes.

- Keep changes focused and modular.
- Update documentation with affected code, configuration, SQL, scripts, or behavior.
- Test before delivery and report commands and results.
- Use Git; the designated master repository is the canonical source of truth.
- Never commit `.env` files, credentials, logs, caches, or generated runtime data.
'

write_file 'SECURITY.md' '# Security

Do not commit credentials, API keys, database passwords, license keys, private certificates, or real `.env` files.

Report suspected vulnerabilities privately to the project owner. Do not publish exploit details, secrets, or customer data in issues, commits, logs, or documentation.

See `system/docs/security.md` and `system/docs/error_handling.md` for global requirements.
'

write_file 'CHANGELOG.md' '# Changelog

All notable project changes should be recorded here.

## Unreleased

- Initial system and application documentation baseline created.
'

write_file 'LICENSE.md' '# License

License terms have not yet been specified by the project owner.

Do not assume an open-source license or redistribute this project until the owner provides an approved license.
'

write_file 'system/docs/README.md' '# System Documentation

This directory is the authoritative source for global system definitions and development rules.

Application documentation under `apps/<app_name>/docs/` may add application-specific requirements or explicitly override a global default for that application. Application documentation must not weaken global security, quality, testing, or agent rules.

## Documents

- [Project overview](project_overview.md)
- [Architecture](architecture.md)
- [Development](development.md)
- [Configuration](configuration.md)
- [Git workflow](git_workflow.md)
- [Coding standards](coding_standards.md)
- [Error handling](error_handling.md)
- [Testing standards](testing_standards.md)
- [Security](security.md)
- [Database](database.md)
- [Deployment](deployment.md)
- [Operations](operations.md)
- [Troubleshooting](troubleshooting.md)
- [AI agent rules](ai_agent_rules.md)
- [Documentation standard](documentation_standard.md)
'

write_file 'system/docs/project_overview.md' '# Project Overview

This project is a PHP-based multi-application platform.

- The `system/` layer contains global shared code, configuration, resources, scripts, data conventions, and documentation.
- The `apps/` layer contains individual applications.
- Each application is responsible for documenting its purpose, configuration overrides, dependencies, database behavior, testing, and deployment requirements in `apps/<app_name>/docs/`.
- The master repository is the canonical single source of truth for versioned project code.
'

write_file 'system/docs/architecture.md' '# Architecture

## Two Level Structure

### System Level

`system/` contains shared functionality and standards used by more than one application. A system-level change may affect multiple applications and must be evaluated accordingly.

### Application Level

`apps/<app_name>/` contains one application and its application-specific code, configuration overrides, resources, and documentation. An application change should be isolated unless it intentionally changes shared system behavior.

## Documentation Precedence

1. Root `AGENTS.md` defines mandatory rules for all work.
2. `system/docs/` defines global standards and defaults.
3. `apps/<app_name>/AGENTS.md` may add rules for one application.
4. `apps/<app_name>/docs/` may document an explicit application-specific override.

No application document may weaken global safety, error handling, testing, security, or confirmation requirements.
'

write_file 'system/docs/configuration.md' '# Configuration

## Environment Files

- The global `.env` defines shared paths and defaults.
- Each application may provide `apps/<app_name>/.env` for application-only overrides.
- Application values override matching global values only for that application.
- Commit `.env.example` files; do not commit real `.env` files.

## Required Rules

- Load configuration in a documented deterministic order.
- Do not hard-code filesystem paths, credentials, API keys, passwords, licenses, or environment-specific URLs.
- Validate required configuration before performing work.
- Return actionable errors without exposing secret values.
- Document every supported variable in the applicable `.env.example` and application documentation.
'

write_file 'system/docs/git_workflow.md' '# Git Workflow

- The designated master repository is the canonical single source of truth.
- Use Git commits and approved synchronization workflows; do not copy source files between repositories as a version-control process.
- Run `git status` before and after work.
- Keep commits focused and clearly described.
- Do not commit `.env`, logs, caches, generated runtime files, passwords, API keys, license keys, or other secrets.
- Changes to `system/` require consideration of all affected applications.
'

write_file 'system/docs/coding_standards.md' '# Coding Standards

## Technology

Use Bash on macOS and Linux, PHP, HTML, JavaScript, Bootstrap 5, Font Awesome, DataTables, and MySQL. Use AWK or Python only when appropriate. Do not add Node.js, npm, Composer, Docker, frameworks, packages, or external dependencies without explicit approval.

## Style

- Use modular structured programming.
- Do not use object-oriented architecture by default.
- Limit objects to cases where they provide clear value, including MySQL/PDO access.
- Keep functions small, focused, and reusable.
- Separate configuration, data access, business logic, output, and UI behavior.
- Avoid duplicate logic and hard-coded values.
- Use lowercase `snake_case` for project-created file and directory names; hyphens are prohibited.
'

write_file 'system/docs/error_handling.md' '# Error Handling

Production code must handle failure paths.

- Validate input before processing.
- Check errors from filesystem operations, shell commands, database calls, network operations, and APIs.
- Use safe behavior for authorization, permissions, and secrets.
- Log actionable diagnostic details where logging is available.
- Do not display credentials, secrets, SQL internals, full stack traces, or sensitive paths to end users.
- Return or display useful, non-sensitive error messages.
'

write_file 'system/docs/testing_standards.md' '# Testing Standards

Before delivering code:

1. Run applicable syntax checks.
2. Run applicable PHP, Bash, SQL, JavaScript, browser, or manual tests.
3. Test expected failures and error paths, not only successful paths.
4. Verify configuration loading and path resolution when affected.
5. Report exact test commands and results.
6. If testing is not possible, state why and identify the unverified risk.

Do not claim code is tested unless the test was actually run.
'

write_file 'system/docs/security.md' '# Security

- Never commit `.env` files, credentials, API keys, database passwords, license keys, private certificates, or customer data.
- Validate and authorize every action using user-supplied input.
- Use least privilege for filesystem and database access.
- Keep application-specific secrets in the applicable application `.env` file.
- Do not expose secrets or internal diagnostics in browser output, logs, documentation, or Git commits.
'

write_file 'system/docs/database.md' '# Database

MySQL is the project database technology.

- Use parameterized queries through PDO or an equivalent approved MySQL interface.
- Keep SQL files organized under the owning system or application directory.
- Document schema ownership, migrations, seed data, and application-specific database overrides in the relevant application documentation.
- Confirm before destructive database operations.
- Test migrations and rollback behavior before delivery.
'

write_file 'system/docs/development.md' '# Development

- Read root `AGENTS.md` before work.
- Load path and environment configuration from `.env` files; do not hard-code local or server paths.
- Read global standards under `system/docs/` and the nearest application documentation before changing an application.
- Use Bash compatible with macOS and Linux for automation.
- Test code before delivery and report what was tested.
'

write_file 'system/docs/deployment.md' '# Deployment

Deployment procedures must use approved project scripts and documented `.env` path configuration.

- Confirm before deployment, destructive changes, or external side effects.
- Validate configuration and permissions before deployment.
- Test deployment steps in a safe environment where possible.
- Verify application health and expected behavior after deployment.
- Document rollback steps before making release changes.
'

write_file 'system/docs/operations.md' '# Operations

- Keep runtime logs separate from source code and do not commit them.
- Use `.env` configuration for paths, credentials, and environment-specific settings.
- Record application-specific operational differences in `apps/<app_name>/docs/`.
- Check logs and error handling when diagnosing failures.
- Maintain documented backup, restore, and rollback procedures when those capabilities are implemented.
'

write_file 'system/docs/troubleshooting.md' '# Troubleshooting

For each issue, record:

1. Symptom and affected application.
2. Relevant non-sensitive log location or error message.
3. Configuration and path checks.
4. Diagnostic commands or queries.
5. Corrective action.
6. Escalation or rollback procedure if the issue persists.

Do not put secrets, credentials, or private customer data in troubleshooting records.
'

write_file 'system/docs/ai_agent_rules.md' '# AI Agent Rules

The root [AGENTS.md](../../AGENTS.md) is mandatory for every AI coding agent and is the authoritative concise rule set.

Agents must read global system documentation and the nearest application rules before work. Agents must not assume missing requirements, must request clarification or confirmation for consequential actions, must include production error handling, must follow modular structured programming, and must test before claiming delivery is complete.
'

write_file 'system/docs/documentation_standard.md' '# Documentation Standard

- Global definitions belong in `system/docs/`.
- Each application may use `apps/<app_name>/docs/` for application-specific behavior and documented overrides.
- Use lowercase `snake_case` for project-created documentation filenames. Hyphens are prohibited.
- Keep documentation in Git with the source it describes.
- Update documentation when behavior, configuration, SQL, scripts, paths, dependencies, security, or operational procedures change.
- Do not document imagined features, commands, APIs, databases, or deployment steps. Document only approved or implemented behavior.
'

for app in "${APPS[@]}"; do
    app_root="apps/$app"
    make_dir "$app_root/docs"
    make_dir "$app_root/data/logs"
    write_file "$app_root/.env.example" "# Application-specific overrides only.\n# Copy to .env for local or deployed values. Do not commit .env.\n# This file overrides matching global .env values for this application only.\n"
    write_file "$app_root/AGENTS.md" "# Application AI Agent Rules\n\nRead the root \\`AGENTS.md\\` and \\`system/docs/README.md\\` before work.\n\nThis application may add requirements but may not weaken global rules for naming, security, confirmation, error handling, structured modular code, or testing.\n\nDocument application-specific configuration, database behavior, dependencies, testing, deployment, and approved overrides in this application's \\`docs/\\` directory. Do not invent application behavior.\n"
    write_file "$app_root/docs/README.md" "# Application Documentation\n\nThis directory contains documentation specific to this application. Global definitions and standards are in \\`system/docs/\\`.\n\nDocument only implemented or approved application behavior. Explicitly identify every application-specific override of a global configuration or standard.\n\n- [Application overview](application_overview.md)\n- [Configuration](configuration.md)\n- [Database](database.md)\n- [Testing](testing.md)\n- [Deployment](deployment.md)\n"
    write_file "$app_root/docs/application_overview.md" "# Application Overview\n\nThis application is located at \\`$app_root\\`.\n\nIts purpose, entry points, dependencies, ownership, and supported behavior have not yet been provided. Add only verified, approved application facts here.\n"
    write_file "$app_root/docs/configuration.md" "# Application Configuration\n\nThis application reads shared defaults from the global `.env` and may override matching values through \\`$app_root/.env\\`.\n\nDocument each implemented application-specific variable, its purpose, whether it is secret, and its validation behavior. Do not record real secret values.\n"
    write_file "$app_root/docs/database.md" "# Application Database\n\nDocument this application's MySQL schema ownership, SQL files, migrations, seed data, connection override behavior, and rollback steps when implemented. Use parameterized PDO queries. Confirm before destructive operations.\n"
    write_file "$app_root/docs/testing.md" "# Application Testing\n\nDocument verified test commands and manual checks for this application when they are implemented. Test successful and error paths. Do not claim tests passed unless they were run.\n"
    write_file "$app_root/docs/deployment.md" "# Application Deployment\n\nDocument approved deployment, verification, and rollback procedures for this application when they are implemented. Confirm before deployment or external side effects.\n"
done

printf '\nCompleted. Review changes with:\n'
printf '  find . -maxdepth 4 -type f | sort\n'
printf '  git status --short\n'
if [ "$DRY_RUN" -eq 1 ]; then
    printf '\nDry run only: no files were changed.\n'
fi
