"""Project scaffolding for generated agents"""

import os
import shutil
from pathlib import Path
from typing import List


class ProjectScaffolder:
    """Creates agent project structure"""

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

    def create_project(self, agent_name: str, code: str, test_yaml: str, dependencies: List[str] = None) -> str:
        """
        Create complete agent project structure

        Args:
            agent_name: Name of the agent (e.g., 'email-extractor')
            code: Main agent code (main.py content)
            test_yaml: Test cases in YAML format
            dependencies: List of Python package dependencies

        Returns:
            str: Path to created project directory
        """
        # Create project directory
        project_path = self.output_dir / agent_name
        if project_path.exists():
            # Backup existing
            backup_path = self.output_dir / f"{agent_name}_backup_{int(os.path.getmtime(project_path))}"
            shutil.move(str(project_path), str(backup_path))

        # Create directory structure
        agent_code_dir = project_path / "agent"
        configs_dir = agent_code_dir / "configs"
        tests_dir = project_path / "tests"

        for dir_path in [agent_code_dir, configs_dir, tests_dir]:
            dir_path.mkdir(parents=True, exist_ok=True)

        # Write files
        self._write_main_code(agent_code_dir, code)
        self._write_init_file(agent_code_dir)
        self._write_config(configs_dir, agent_name)
        self._write_test_cases(tests_dir, agent_name, test_yaml)
        self._write_pyproject_toml(project_path, agent_name, dependencies or [])
        self._write_readme(project_path, agent_name)

        return str(project_path)

    def _write_main_code(self, agent_dir: Path, code: str):
        """Write main.py file"""
        main_path = agent_dir / "main.py"
        main_path.write_text(code, encoding='utf-8')

    def _write_init_file(self, agent_dir: Path):
        """Write __init__.py file"""
        init_path = agent_dir / "__init__.py"
        init_path.write_text("# Agent package\n", encoding='utf-8')

    def _write_config(self, configs_dir: Path, agent_name: str):
        """Write agent.yml config file"""
        config_path = configs_dir / "agent.yml"
        config_content = f"# Configuration for {agent_name}\n"
        config_path.write_text(config_content, encoding='utf-8')

    def _write_test_cases(self, tests_dir: Path, agent_name: str, test_yaml: str):
        """Write test cases YAML file"""
        test_path = tests_dir / f"test_{agent_name.replace('-', '_')}.yml"
        test_path.write_text(test_yaml, encoding='utf-8')

    def _write_pyproject_toml(self, project_path: Path, agent_name: str, dependencies: List[str]):
        """Write pyproject.toml file"""
        # Base dependencies
        base_deps = ["pyarrow>=5.0.0"]
        all_deps = base_deps + dependencies

        deps_str = "\n    ".join([f'"{dep}",' for dep in all_deps])

        content = f'''[build-system]
requires = ["setuptools>=65", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "{agent_name}"
version = "0.1.0"
description = "Auto-generated MoFA agent"
dependencies = [
    {deps_str}
]

[project.scripts]
{agent_name} = "agent.main:main"

[tool.setuptools.packages.find]
include = ["agent*"]
'''
        toml_path = project_path / "pyproject.toml"
        toml_path.write_text(content, encoding='utf-8')

    def _write_readme(self, project_path: Path, agent_name: str):
        """Write README.md file"""
        content = f'''# {agent_name}

Auto-generated MoFA agent created by Vibe.

## Installation

```bash
pip install -e .
```

## Usage

```python
from agent.main import main
main()
```

## Testing

```bash
mofa unit-test . ./tests/test_{agent_name.replace('-', '_')}.yml
```

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