#!/bin/bash

# Reset MkDocs site to baseline while preserving custom code
# Creates a timestamped backup of the entire docs/ folder before any changes
# Usage: ./reset-site.sh

set -e  # Exit on error

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MKDOCS_DIR="$SCRIPT_DIR/mkdocs"
DOCS_DIR="$MKDOCS_DIR/docs"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
BACKUP_DIR="$MKDOCS_DIR/backups/docs_backup_$TIMESTAMP"
TEMP_DIR="/tmp/mkdocs-reset-$$"

# --- Pre-flight checks ---
if [ ! -d "$DOCS_DIR" ]; then
    echo "ERROR: docs directory not found at $DOCS_DIR"
    exit 1
fi

if [ ! -f "$MKDOCS_DIR/mkdocs.yml" ]; then
    echo "ERROR: mkdocs.yml not found at $MKDOCS_DIR/mkdocs.yml"
    exit 1
fi

# --- Full backup before any destructive operations ---
echo "📦 Creating full backup of docs/ and mkdocs.yml..."
mkdir -p "$BACKUP_DIR"
cp -r "$DOCS_DIR" "$BACKUP_DIR/docs"
cp "$MKDOCS_DIR/mkdocs.yml" "$BACKUP_DIR/mkdocs.yml"
echo "   Backup saved to: $BACKUP_DIR"

# Show backup size
BACKUP_SIZE=$(du -sh "$BACKUP_DIR" | cut -f1)
echo "   Backup size: $BACKUP_SIZE"

# --- Confirmation prompt ---
echo ""
echo "WARNING: This will reset the docs/ directory to a baseline MkDocs template."
echo "The following content directories will be DELETED (not in preserve list):"

# Show what will be lost
LOST_DIRS=()
for item in "$DOCS_DIR"/*/; do
    [ ! -d "$item" ] && continue
    dirname="$(basename "$item")"
    case "$dirname" in
        hooks|assets|javascripts|overrides|stylesheets|blog|comments|partials) ;;
        *) LOST_DIRS+=("$dirname") ;;
    esac
done

LOST_FILES=()
for item in "$DOCS_DIR"/*; do
    [ -d "$item" ] && continue
    [ ! -f "$item" ] && continue
    LOST_FILES+=("$(basename "$item")")
done

if [ ${#LOST_DIRS[@]} -gt 0 ]; then
    for d in "${LOST_DIRS[@]}"; do
        echo "   - $d/"
    done
fi
if [ ${#LOST_FILES[@]} -gt 0 ]; then
    for f in "${LOST_FILES[@]}"; do
        echo "   - $f"
    done
fi

echo ""
read -p "Continue with reset? (y/N): " CONFIRM
if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
    echo "Aborted. Backup remains at: $BACKUP_DIR"
    exit 0
fi

echo ""
echo "🔄 Resetting MkDocs site to baseline..."

# Create temp directory for selective restores
mkdir -p "$TEMP_DIR"

# Backup custom directories if they exist
echo "📦 Preserving custom directories..."
for dir in hooks assets javascripts overrides stylesheets blog comments partials; do
    if [ -d "$DOCS_DIR/$dir" ]; then
        echo "  - Preserving $dir/"
        cp -r "$DOCS_DIR/$dir" "$TEMP_DIR/"
    fi
done

# Backup mkdocs.yml
cp "$MKDOCS_DIR/mkdocs.yml" "$TEMP_DIR/mkdocs.yml.bak"

# Clear docs directory
echo "🧹 Clearing docs directory..."
rm -rf "$DOCS_DIR"/*
rm -rf "$DOCS_DIR"/.*  2>/dev/null || true

# Create baseline MkDocs Material structure
echo "📝 Creating baseline content structure..."
mkdir -p "$DOCS_DIR"

# Create index.md
cat > "$DOCS_DIR/index.md" << 'EOF'
# Welcome to Your MkDocs Site

This site has been reset to baseline configuration.

## Getting Started

- Edit `docs/index.md` to change this page
- Add new pages in the `docs/` directory
- Configure navigation in `mkdocs.yml`
- Customize the theme in `docs/overrides/`

## Features Preserved

Your custom code has been preserved in:

- `hooks/` - Custom build hooks
- `assets/` - Images and static files
- `javascripts/` - Custom JavaScript
- `overrides/` - Theme overrides
- `stylesheets/` - Custom CSS
- `blog/` - Blog content

## Next Steps

1. Start adding your content
2. Configure the navigation
3. Customize the appearance
4. Deploy your site

---

*Built with MkDocs Material*
EOF

# Create a simple getting-started.md
cat > "$DOCS_DIR/getting-started.md" << 'EOF'
# Getting Started

Welcome to your fresh MkDocs Material site!

## Adding Content

Create new markdown files in the `docs/` directory:

```bash
docs/
├── index.md          # Homepage
├── getting-started.md # This page
├── page1.md          # Your content
└── page2.md          # More content
```

## Configuring Navigation

Edit `mkdocs.yml` to add navigation:

```yaml
nav:
  - Home: index.md
  - Getting Started: getting-started.md
  - Your Section:
    - Page 1: page1.md
    - Page 2: page2.md
```

## Using the Blog

The blog plugin is already configured. Add posts in `docs/blog/posts/`:

```markdown
---
date: 2024-01-01
categories:
  - News
---

# Your Blog Post Title

Post content here...
```

## Customization

- Theme overrides: `docs/overrides/`
- Custom CSS: `docs/stylesheets/`
- Custom JS: `docs/javascripts/`
EOF

# Restore custom directories
echo "♻️ Restoring custom directories..."
for dir in hooks assets javascripts overrides stylesheets blog comments partials; do
    if [ -d "$TEMP_DIR/$dir" ]; then
        echo "  - Restoring $dir/"
        cp -r "$TEMP_DIR/$dir" "$DOCS_DIR/"
    else
        # Create empty directories if they didn't exist
        mkdir -p "$DOCS_DIR/$dir"
    fi
done

# Create simplified home.html (only if not restored from backup)
if [ -f "$DOCS_DIR/overrides/home.html" ]; then
    echo "🏠 Existing home.html preserved (skipping template creation)"
else
echo "🏠 Creating simplified home template..."
cat > "$DOCS_DIR/overrides/home.html" << 'EOF'
{% extends "main.html" %}

{% block extrahead %}
{{ super() }}
<link rel="stylesheet" href="{{ 'stylesheets/home.css' | url }}">
{% endblock %}

{% block content %}
<div class="home-container">
    <div class="home-hero">
        {% if config.theme.logo %}
        <img src="{{ config.theme.logo | url }}" alt="Logo" class="home-logo">
        {% endif %}

        <h1 class="home-title">Let's get started!</h1>

        <p class="home-subtitle">
            Your MkDocs Material site is ready for customization.
        </p>

        <div class="home-actions">
            <a href="{{ 'getting-started/' | url }}" class="home-button home-button-primary">
                Get Started
            </a>
            <a href="https://squidfunk.github.io/mkdocs-material/" class="home-button home-button-secondary">
                Documentation
            </a>
        </div>
    </div>

    <div class="home-features">
        <div class="feature-card">
            <div class="feature-icon">📝</div>
            <h3>Write Content</h3>
            <p>Create pages with Markdown</p>
        </div>

        <div class="feature-card">
            <div class="feature-icon">🎨</div>
            <h3>Customize Theme</h3>
            <p>Make it your own</p>
        </div>

        <div class="feature-card">
            <div class="feature-icon">🚀</div>
            <h3>Deploy</h3>
            <p>Share with the world</p>
        </div>
    </div>
</div>
{% endblock %}
EOF

fi

# Create simplified home.css (only if not restored from backup)
if [ -f "$DOCS_DIR/stylesheets/home.css" ]; then
    echo "🎨 Existing home.css preserved (skipping template creation)"
else
echo "🎨 Creating simplified home styles..."
cat > "$DOCS_DIR/stylesheets/home.css" << 'EOF'
/* Simple home page styles */

.home-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;
}

.home-hero {
    text-align: center;
    padding: 4rem 0;
}

.home-logo {
    width: 120px;
    height: 120px;
    margin-bottom: 2rem;
}

.home-title {
    font-size: 3rem;
    font-weight: 700;
    margin: 0 0 1rem 0;
    color: var(--md-primary-fg-color);
}

.home-subtitle {
    font-size: 1.25rem;
    color: var(--md-default-fg-color--light);
    margin: 0 0 2rem 0;
}

.home-actions {
    display: flex;
    gap: 1rem;
    justify-content: center;
    flex-wrap: wrap;
}

.home-button {
    display: inline-block;
    padding: 0.75rem 2rem;
    border-radius: 0.25rem;
    text-decoration: none;
    font-weight: 500;
    transition: all 0.2s;
}

.home-button-primary {
    background: var(--md-primary-fg-color);
    color: var(--md-primary-bg-color);
}

.home-button-primary:hover {
    background: var(--md-primary-fg-color--dark);
    transform: translateY(-2px);
}

.home-button-secondary {
    border: 2px solid var(--md-primary-fg-color);
    color: var(--md-primary-fg-color);
}

.home-button-secondary:hover {
    background: var(--md-primary-fg-color);
    color: var(--md-primary-bg-color);
}

.home-features {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 2rem;
    margin-top: 4rem;
}

.feature-card {
    text-align: center;
    padding: 2rem;
    border-radius: 0.5rem;
    background: var(--md-code-bg-color);
}

.feature-icon {
    font-size: 3rem;
    margin-bottom: 1rem;
}

.feature-card h3 {
    margin: 0 0 0.5rem 0;
    color: var(--md-default-fg-color);
}

.feature-card p {
    margin: 0;
    color: var(--md-default-fg-color--light);
}

/* Dark mode support */
[data-md-color-scheme="slate"] .home-logo {
    filter: brightness(0.9);
}

[data-md-color-scheme="slate"] .feature-card {
    background: var(--md-default-fg-color--lightest);
}

/* Mobile responsive */
@media (max-width: 768px) {
    .home-title {
        font-size: 2rem;
    }

    .home-subtitle {
        font-size: 1rem;
    }

    .home-actions {
        flex-direction: column;
        align-items: center;
    }

    .home-button {
        width: 100%;
        max-width: 300px;
        text-align: center;
    }
}
EOF

fi

# Update mkdocs.yml - remove nav section
echo "📋 Updating mkdocs.yml (removing nav)..."
# Use Python to safely remove the nav block without eating adjacent sections
python3 -c "
import re, sys
with open(sys.argv[1], 'r') as f:
    content = f.read()
# Remove 'nav:' line and all following indented lines (the entire nav block)
content = re.sub(r'^nav:[ \t]*\n(?:[ \t]+.*\n)*', '', content, flags=re.MULTILINE)
with open(sys.argv[1], 'w') as f:
    f.write(content)
" "$MKDOCS_DIR/mkdocs.yml"

# Also ensure the logo path is correct
if [ -f "$DOCS_DIR/assets/logo.png" ]; then
    echo "✅ Logo found at assets/logo.png"
else
    echo "⚠️  No logo found at assets/logo.png - you may want to add one"
fi

# Clean up temp directory
rm -rf "$TEMP_DIR"

echo ""
echo "✅ Reset complete!"
echo ""
echo "Backup location: $BACKUP_DIR"
echo "  To restore: rm -rf $DOCS_DIR && cp -r $BACKUP_DIR/docs $DOCS_DIR && cp $BACKUP_DIR/mkdocs.yml $MKDOCS_DIR/mkdocs.yml"
echo ""
echo "Next steps:"
echo "1. Add your content to $DOCS_DIR"
echo "2. Configure navigation in mkdocs.yml"
echo "3. Customize the home page in overrides/home.html"
echo "4. Run 'mkdocs serve' to preview"
echo ""
echo "Your custom code has been preserved in:"
echo "  - hooks/"
echo "  - assets/"
echo "  - javascripts/"
echo "  - overrides/"
echo "  - stylesheets/"
echo "  - blog/"
echo "  - comments/"
echo "  - partials/"
