"""Flow scaffolding for generated flows"""

import os
from pathlib import Path
from typing import List, Dict


class FlowScaffolder:
    """Creates flow project structure"""

    def __init__(self, output_dir: str = "./flows"):
        self.output_dir = Path(output_dir)

    def create_flow(self, flow_name: str, flow_yaml: str, agents: List[str] = None) -> str:
        """
        Create complete flow project structure

        Args:
            flow_name: Name of the flow (e.g., 'weather-forecast')
            flow_yaml: Flow dataflow YAML content
            agents: List of agent names used in the flow

        Returns:
            str: Path to created flow directory
        """
        # Create flow directory
        flow_path = self.output_dir / flow_name
        flow_path.mkdir(parents=True, exist_ok=True)

        # Create subdirectories
        out_dir = flow_path / "out"
        out_dir.mkdir(exist_ok=True)

        # Write files
        self._write_dataflow_yaml(flow_path, flow_name, flow_yaml)
        self._write_gitignore(flow_path)
        self._write_readme(flow_path, flow_name, agents or [])

        return str(flow_path)

    def _write_dataflow_yaml(self, flow_path: Path, flow_name: str, flow_yaml: str):
        """Write dataflow YAML file"""
        yaml_path = flow_path / f"{flow_name}_dataflow.yml"
        yaml_path.write_text(flow_yaml, encoding='utf-8')

    def _write_gitignore(self, flow_path: Path):
        """Write .gitignore file"""
        gitignore_content = """# Output files
out/
*.log

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
venv/
env/
ENV/

# MoFA runtime
mofa_run_*/
"""
        gitignore_path = flow_path / ".gitignore"
        gitignore_path.write_text(gitignore_content, encoding='utf-8')

    def _write_readme(self, flow_path: Path, flow_name: str, agents: List[str]):
        """Write README.md file"""
        agents_list = "\n".join([f"- {agent}" for agent in agents]) if agents else "- (none specified)"

        content = f'''# {flow_name}

Auto-generated MoFA flow created by Vibe.

## Flow Structure

This flow connects the following agents:
{agents_list}

## Installation

Make sure all required agents are installed:

```bash
# Install agents as needed
# Example: mofa download <agent-name>
```

## Usage

Run the flow:

```bash
mofa run-flow ./{flow_name}_dataflow.yml
```

## Flow Configuration

The flow dataflow is defined in `{flow_name}_dataflow.yml`. You can modify this file to:
- Add or remove nodes
- Change connections between agents
- Configure environment variables
- Set build commands

---
Generated by MoFA Vibe
'''
        readme_path = flow_path / "README.md"
        readme_path.write_text(content, encoding='utf-8')
