import { cp, rm, readdir, mkdir, writeFile, stat } from 'fs/promises';
import path from 'path';
import { env } from '../../config/env';
import { logger } from '../../utils/logger';
import { docsFilesService } from './docs-files.service';
import { mkdocsConfigService } from './mkdocs-config.service';

const PRESERVED_DIRS = [
  'hooks',
  'assets',
  'javascripts',
  'overrides',
  'stylesheets',
  'blog',
  'comments',
  'partials',
  'includes',
];

const BASELINE_INDEX_MD = `# 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*
`;

const BASELINE_GETTING_STARTED_MD = `# Getting Started

Welcome to your fresh MkDocs Material site!

## Adding Content

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

\`\`\`bash
docs/
\u251c\u2500\u2500 index.md          # Homepage
\u251c\u2500\u2500 getting-started.md # This page
\u251c\u2500\u2500 page1.md          # Your content
\u2514\u2500\u2500 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/\`
`;

const HOME_HTML = `{% 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 %}
`;

const HOME_CSS = `/* 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;
    }
}
`;

interface ResetResult {
  success: boolean;
  backupPath: string;
  filesReset: number;
  filesPreserved: number;
}

async function resetToBaseline(): Promise<ResetResult> {
  const docsDir = path.resolve(env.MKDOCS_DOCS_PATH);
  const mkdocsRoot = path.dirname(env.MKDOCS_CONFIG_PATH);
  const timestamp = new Date().toISOString().replace(/[:.]/g, '').replace('T', '_').slice(0, 15);
  const backupDir = path.join(mkdocsRoot, 'backups', `docs_backup_${timestamp}`);
  const tempDir = path.join('/tmp', `mkdocs-reset-${process.pid}`);

  logger.info('Starting docs reset to baseline', { docsDir, backupDir });

  // Step a: Create timestamped backup
  await mkdir(backupDir, { recursive: true });
  await cp(docsDir, path.join(backupDir, 'docs'), { recursive: true });
  await cp(env.MKDOCS_CONFIG_PATH, path.join(backupDir, 'mkdocs.yml'));
  logger.info('Backup created', { backupDir });

  // Step b: Save preserved directories to temp
  await mkdir(tempDir, { recursive: true });
  let filesPreserved = 0;

  for (const dir of PRESERVED_DIRS) {
    const srcDir = path.join(docsDir, dir);
    try {
      const info = await stat(srcDir);
      if (info.isDirectory()) {
        await cp(srcDir, path.join(tempDir, dir), { recursive: true });
        filesPreserved++;
        logger.info(`Preserved directory: ${dir}`);
      }
    } catch {
      // Directory doesn't exist, skip
    }
  }

  // Step c: Clear the docs directory
  const entries = await readdir(docsDir);
  for (const entry of entries) {
    await rm(path.join(docsDir, entry), { recursive: true, force: true });
  }
  logger.info('Docs directory cleared');

  // Step d: Write baseline content
  let filesReset = 0;
  await writeFile(path.join(docsDir, 'index.md'), BASELINE_INDEX_MD, 'utf-8');
  filesReset++;
  await writeFile(path.join(docsDir, 'getting-started.md'), BASELINE_GETTING_STARTED_MD, 'utf-8');
  filesReset++;

  // Step e: Restore preserved directories from temp
  for (const dir of PRESERVED_DIRS) {
    const tempSrcDir = path.join(tempDir, dir);
    try {
      const info = await stat(tempSrcDir);
      if (info.isDirectory()) {
        await cp(tempSrcDir, path.join(docsDir, dir), { recursive: true });
        logger.info(`Restored directory: ${dir}`);
      }
    } catch {
      // Wasn't preserved, create empty directory
      await mkdir(path.join(docsDir, dir), { recursive: true });
    }
  }

  // Step f: Create home.html and home.css templates if they don't exist in preserved overrides/stylesheets
  const homeHtmlPath = path.join(docsDir, 'overrides', 'home.html');
  try {
    await stat(homeHtmlPath);
    logger.info('Existing home.html preserved');
  } catch {
    await mkdir(path.join(docsDir, 'overrides'), { recursive: true });
    await writeFile(homeHtmlPath, HOME_HTML, 'utf-8');
    filesReset++;
    logger.info('Created baseline home.html');
  }

  const homeCssPath = path.join(docsDir, 'stylesheets', 'home.css');
  try {
    await stat(homeCssPath);
    logger.info('Existing home.css preserved');
  } catch {
    await mkdir(path.join(docsDir, 'stylesheets'), { recursive: true });
    await writeFile(homeCssPath, HOME_CSS, 'utf-8');
    filesReset++;
    logger.info('Created baseline home.css');
  }

  // Clean up temp directory
  await rm(tempDir, { recursive: true, force: true }).catch(() => {});

  // Step g: Invalidate docs file tree cache
  await docsFilesService.invalidateTreeCache();

  // Step h: Trigger a build
  const buildResult = await mkdocsConfigService.triggerBuild();
  if (!buildResult.success) {
    logger.warn('MkDocs build after reset did not succeed', { output: buildResult.output });
  }

  logger.info('Docs reset to baseline complete', { filesReset, filesPreserved, backupDir });

  return {
    success: true,
    backupPath: backupDir,
    filesReset,
    filesPreserved,
  };
}

export const docsResetService = {
  resetToBaseline,
};
