import subprocess
from pathlib import Path
from rich.console import Console
from ..models import RunManifest
from ..utils.vitepress import assemble_site


def output_step(manifest: RunManifest):
    output_path = manifest.config.output_path
    project_path = manifest.config.project_path
    console = Console()

    console.print(f"Generating VitePress documentation at {output_path}...")

    # Determine screenshots directory
    screenshots_dir = str(project_path / ".kodadocs" / "screenshots")

    # Extract parameters from manifest for the shared assembler
    result = assemble_site(
        articles=manifest.articles,
        screenshots_dir=screenshots_dir,
        brand_color=manifest.config.brand_color or "#3e8fb0",
        logo_path=str(manifest.config.logo_path) if manifest.config.logo_path else None,
        output_dir=str(output_path),
        project_name=project_path.name,
        product_summary=manifest.product_summary or "",
        discovered_routes=manifest.discovered_routes,
        theme_name=getattr(manifest.config, "theme_name", "default"),
    )

    if result.get("warnings"):
        for warning in result["warnings"]:
            console.print(f"[yellow]{warning}[/yellow]")

    console.print(
        f"[bold green]Documentation generated successfully in {output_path}[/bold green]"
    )

    # Generate README
    (output_path / "README.md").write_text(f"""# {project_path.name} Documentation

Generated by KodaDocs.

## Running Locally

1. Install dependencies:
   ```bash
   npm install
   ```

2. Start the dev server:
   ```bash
   npm run docs:dev
   ```

3. Build for production:
   ```bash
   npm run docs:build
   ```
""")

    # Automated Build Step
    def run_command(cmd, cwd):
        try:
            console.print(f"Running '{' '.join(cmd)}' in {cwd}...")
            subprocess.run(cmd, cwd=cwd, check=True, capture_output=True)
            return True
        except subprocess.CalledProcessError as e:
            console.print(f"[red]Command failed: {e.stderr.decode()}[/red]")
            return False
        except FileNotFoundError:
            console.print(f"[red]Command not found: {cmd[0]}[/red]")
            return False

    if (output_path / "package.json").exists():
        console.print("Starting automated VitePress build...")
        if run_command(["npm", "install"], output_path):
            if run_command(["npm", "run", "docs:build"], output_path):
                console.print(
                    "[bold green]VitePress site built successfully![/bold green]"
                )
                console.print(
                    f"Static files are ready in: {output_path / '.vitepress' / 'dist'}"
                )
            else:
                console.print(
                    "[yellow]Build failed. You may need to run 'npm run docs:build' manually.[/yellow]"
                )
        else:
            console.print(
                "[yellow]Install failed. Please ensure Node.js and npm are installed.[/yellow]"
            )

    console.print(
        "Run 'npm run docs:dev' in the docs folder to start a local preview server."
    )
