"""Generate test artifacts for manual inspection."""

import pathlib
import shutil
from colight_site.builder import build_directory


def test_generate_artifacts_for_inspection():
    """Generate various colight-site examples in test-artifacts for manual inspection."""

    # Get paths
    test_dir = pathlib.Path(__file__).parent
    examples_dir = test_dir / "examples"
    project_root = test_dir.parent.parent.parent  # Go up 3 levels to project root
    artifacts_dir = project_root / "test-artifacts" / "colight-site"

    # Create test-artifacts directory
    artifacts_dir.mkdir(parents=True, exist_ok=True)

    # Clean up any existing files
    for file in artifacts_dir.rglob("*"):
        if file.is_file():
            file.unlink()
    for dir in artifacts_dir.rglob("*"):
        if dir.is_dir() and dir != artifacts_dir:
            try:
                dir.rmdir()
            except OSError:
                pass

    # Copy all example files to artifacts directory
    if examples_dir.exists():
        for source_file in examples_dir.glob("*.colight.py"):
            shutil.copy2(source_file, artifacts_dir / source_file.name)

    # Use the existing build_directory function to generate both markdown and HTML
    print("Building markdown files...")
    build_directory(artifacts_dir, artifacts_dir, verbose=True, format="markdown")

    print("Building HTML files...")
    build_directory(artifacts_dir, artifacts_dir, verbose=True, format="html")

    # Create an index file dynamically
    example_files = sorted([f for f in artifacts_dir.glob("*.colight.py")])

    index_content = """# colight-site Test Artifacts

This directory contains test artifacts generated by colight-site for manual inspection.

## Examples

"""

    # Add discovered examples to the index
    for i, example_file in enumerate(example_files, 1):
        name = example_file.stem
        index_content += (
            f"{i}. **{name}** - Generated from {example_file.name} (.md and .html)\n"
        )

    index_content += """
## Files Generated

For each `.colight.py` source file, colight-site automatically generates:
- A `.md` markdown file with the narrative and code blocks  
- A `.html` file with styled HTML output and embedded visualizations
- A `_colight/` directory containing `.colight` visualization files
- Each visualization is embedded using `<div class="colight-embed" data-src="...">` tags

## Viewing

You can view the generated markdown and HTML files. The HTML files include complete styling and can be opened directly in a browser. You can also inspect the `.colight` files in the `*_colight/` directories to see how visualizations are serialized.

## How It Works

This test automatically discovers all `.colight.py` files in the examples directory and processes them using the `build_directory()` function from colight-site. No manual file listing is required - new examples are automatically included.

## Data Types Support

colight-site automatically visualizes various Python data types:
- Python primitives (int, float, str, bool, None)
- Collections (lists, tuples, sets, dictionaries) 
- NumPy arrays with different shapes and dtypes
- Datetime objects (datetime, date, time)
- Custom objects with attributes
- Nested and complex data structures
- Large collections (with automatic handling)
- Unicode and special characters

Complex data types get rich, interactive visualizations while simple types use default representations.
"""

    (artifacts_dir / "README.md").write_text(index_content)

    print(f"\nGenerated test artifacts in: {artifacts_dir}")
    print("Files created:")
    for file in sorted(artifacts_dir.rglob("*")):
        if file.is_file():
            print(f"  {file.relative_to(artifacts_dir)}")


if __name__ == "__main__":
    test_generate_artifacts_for_inspection()
