"""Module for generating architecture structures."""

from pathlib import Path
from prozes.modules.console import print_creating, print_success, console
from prozes.modules.i18n import t


# =============================================================================
# TEMPLATES COMUNS
# =============================================================================

GITIGNORE_CONTENT = '''# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# Virtual environment
venv/
.venv/
ENV/

# IDE
.idea/
.vscode/
*.swp
*.swo

# Environment variables
.env
.env.local

# Distribution / packaging
dist/
build/
*.egg-info/

# Testing
.pytest_cache/
.coverage
htmlcov/

# OS
.DS_Store
Thumbs.db
'''

CONFIG_INIT = '''"""Configuracoes da aplicacao."""

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent


class Config:
    """Configuracao base."""
    SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-secret-key')
    DEBUG = False


class DevelopmentConfig(Config):
    """Configuracao de desenvolvimento."""
    DEBUG = True


class ProductionConfig(Config):
    """Configuracao de producao."""
    pass
'''

TESTS_INIT = '''"""Testes da aplicacao."""
'''

TEST_PLACEHOLDER = '''"""Testes basicos da aplicacao."""

import pytest


def test_placeholder():
    """Teste placeholder."""
    assert True
'''

ENV_EXAMPLE = '''# Application
SECRET_KEY=your-secret-key-change-this-in-production
DEBUG=True

# Database (if needed)
# DATABASE_URL=sqlite:///app.db
# DATABASE_URL=postgresql://user:password@localhost:5432/dbname

# API Keys (if needed)
# API_KEY=your-api-key-here
'''

REQUIREMENTS_DEV = '''-r requirements.txt

# Development tools
pytest>=8.0.0
pytest-cov>=4.1.0
black>=24.0.0
ruff>=0.2.0

# Optional: API testing
# httpx>=0.24.0
'''

PYTEST_CONFIG = '''[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
python_functions = ["test_*"]
addopts = "-v --tb=short"

[tool.coverage.run]
source = ["."]
omit = ["tests/*", "venv/*"]
'''

GITHUB_WORKFLOW_TEST = '''name: Tests

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main, develop]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.11"

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
          pip install pytest pytest-cov

      - name: Run tests
        run: |
          pytest --cov --cov-report=term-missing
'''

LOGGING_CONFIG = '''"""Configuracao de logging."""

import logging
import sys

def setup_logging(level=logging.INFO):
    """Configura logging da aplicacao."""
    logging.basicConfig(
        level=level,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.StreamHandler(sys.stdout),
            logging.FileHandler('app.log')
        ]
    )

    return logging.getLogger(__name__)
'''

TEST_FLASK_MVC = '''"""Testes da aplicacao Flask MVC."""

import pytest
from main import app


@pytest.fixture
def client():
    """Fixture do cliente de teste."""
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client


def test_app_exists(client):
    """Testa se a aplicacao existe."""
    assert app is not None


def test_index_route(client):
    """Testa a rota principal."""
    response = client.get('/')
    assert response.status_code == 200
'''

TEST_FASTAPI_MVC = '''"""Testes da aplicacao FastAPI MVC."""

import pytest
from fastapi.testclient import TestClient
from main import app


@pytest.fixture
def client():
    """Fixture do cliente de teste."""
    return TestClient(app)


def test_app_exists():
    """Testa se a aplicacao existe."""
    assert app is not None


def test_root_route(client):
    """Testa a rota principal."""
    response = client.get('/')
    assert response.status_code == 200
'''

TEST_FLASK_API = '''"""Testes da API Flask."""

import pytest
from main import app


@pytest.fixture
def client():
    """Fixture do cliente de teste."""
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client


def test_health_check(client):
    """Testa o health check."""
    response = client.get('/api/health')
    assert response.status_code == 200
    assert response.json['status'] == 'ok'


def test_list_items(client):
    """Testa a listagem de items."""
    response = client.get('/api/v1/items')
    assert response.status_code == 200
    assert 'items' in response.json
'''

TEST_FASTAPI_API = '''"""Testes da API FastAPI."""

import pytest
from fastapi.testclient import TestClient
from main import app


@pytest.fixture
def client():
    """Fixture do cliente de teste."""
    return TestClient(app)


def test_health_check(client):
    """Testa o health check."""
    response = client.get('/api/health')
    assert response.status_code == 200
    assert response.json()['status'] == 'ok'


def test_list_items(client):
    """Testa a listagem de items."""
    response = client.get('/api/v1/items')
    assert response.status_code == 200
    assert 'items' in response.json()
'''

TEST_CLI = '''"""Testes do CLI."""

import pytest
from click.testing import CliRunner
from {project_name}.main import cli


@pytest.fixture
def runner():
    """Fixture do CLI runner."""
    return CliRunner()


def test_cli_help(runner):
    """Testa o help do CLI."""
    result = runner.invoke(cli, ['--help'])
    assert result.exit_code == 0
    assert 'Usage' in result.output


def test_hello_command(runner):
    """Testa o comando hello."""
    result = runner.invoke(cli, ['hello'])
    assert result.exit_code == 0
'''


# =============================================================================
# TEMPLATES FLASK MVC
# =============================================================================

FLASK_MAIN_PY = '''"""Aplicacao Flask principal."""

from flask import Flask

app = Flask(__name__)


@app.route('/')
def index():
    return 'Hello, World!'


if __name__ == '__main__':
    app.run(debug=True)
'''

FLASK_APP_INIT = '''"""Inicializacao do pacote app."""

from flask import Flask


def create_app():
    """Factory function para criar a aplicacao Flask."""
    app = Flask(__name__)

    app.config.from_mapping(
        SECRET_KEY='dev',
    )

    from app.controllers import main_bp
    app.register_blueprint(main_bp)

    return app
'''

FLASK_CONTROLLER = '''"""Controllers principais da aplicacao."""

from flask import Blueprint, render_template

main_bp = Blueprint('main', __name__)


@main_bp.route('/')
def index():
    """Pagina inicial."""
    return render_template('base.html')
'''

FLASK_BASE_TEMPLATE = '''<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title if title else 'Minha Aplicacao' }}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <main>
        {% block content %}
        <h1>Bem-vindo!</h1>
        {% endblock %}
    </main>
    <script src="{{ url_for('static', filename='js/main.js') }}"></script>
</body>
</html>
'''

FLASK_CSS = '''/* Estilos principais */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    line-height: 1.6;
    padding: 2rem;
}

main {
    max-width: 1200px;
    margin: 0 auto;
}
'''

FLASK_JS = '''// JavaScript principal
console.log('Aplicacao carregada');
'''


# =============================================================================
# TEMPLATES FASTAPI MVC
# =============================================================================

FASTAPI_MAIN_PY = '''"""Aplicacao FastAPI principal."""

import uvicorn
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

from app.controllers import router

app = FastAPI(title="Minha API", version="1.0.0")

# Static files e templates
app.mount("/static", StaticFiles(directory="app/static"), name="static")
templates = Jinja2Templates(directory="app/templates")

# Registrar rotas
app.include_router(router)


@app.get("/")
async def root():
    return {"message": "Hello, World!"}


if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
'''

FASTAPI_APP_INIT = '''"""Inicializacao do pacote app."""

from fastapi import FastAPI


def create_app() -> FastAPI:
    """Factory function para criar a aplicacao FastAPI."""
    app = FastAPI(
        title="Minha API",
        version="1.0.0",
    )

    from app.controllers import router
    app.include_router(router)

    return app
'''

FASTAPI_CONTROLLER = '''"""Controllers principais da aplicacao."""

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

router = APIRouter()
templates = Jinja2Templates(directory="app/templates")


@router.get("/hello")
async def hello():
    """Endpoint de exemplo."""
    return {"message": "Hello from controller!"}


@router.get("/page", response_class=HTMLResponse)
async def page(request: Request):
    """Pagina de exemplo."""
    return templates.TemplateResponse("base.html", {"request": request})
'''

FASTAPI_BASE_TEMPLATE = '''<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title if title else 'Minha Aplicacao' }}</title>
    <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
    <main>
        <h1>Bem-vindo!</h1>
    </main>
    <script src="/static/js/main.js"></script>
</body>
</html>
'''


# =============================================================================
# TEMPLATES API REST (sem frontend)
# =============================================================================

FLASK_API_MAIN = '''"""API REST Flask."""

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/api/health')
def health():
    return jsonify({"status": "ok"})


@app.route('/api/v1/items', methods=['GET'])
def list_items():
    return jsonify({"items": []})


@app.route('/api/v1/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    return jsonify({"id": item_id, "name": "Item exemplo"})


if __name__ == '__main__':
    app.run(debug=True)
'''

FLASK_API_ROUTES = '''"""Rotas da API."""

from flask import Blueprint, jsonify, request

api_bp = Blueprint('api', __name__, url_prefix='/api/v1')


@api_bp.route('/items', methods=['GET'])
def list_items():
    """Lista todos os items."""
    return jsonify({"items": []})


@api_bp.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    """Retorna um item pelo ID."""
    return jsonify({"id": item_id, "name": "Item exemplo"})


@api_bp.route('/items', methods=['POST'])
def create_item():
    """Cria um novo item."""
    data = request.get_json()
    return jsonify({"id": 1, **data}), 201
'''

FASTAPI_API_MAIN = '''"""API REST FastAPI."""

import uvicorn
from fastapi import FastAPI

from app.routes import router

app = FastAPI(
    title="Minha API",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
)

app.include_router(router, prefix="/api/v1")


@app.get("/api/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
'''

FASTAPI_API_ROUTES = '''"""Rotas da API."""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional

router = APIRouter()


class ItemCreate(BaseModel):
    name: str
    description: Optional[str] = None


class ItemResponse(BaseModel):
    id: int
    name: str
    description: Optional[str] = None


@router.get("/items")
async def list_items():
    """Lista todos os items."""
    return {"items": []}


@router.get("/items/{item_id}")
async def get_item(item_id: int):
    """Retorna um item pelo ID."""
    return {"id": item_id, "name": "Item exemplo"}


@router.post("/items", response_model=ItemResponse, status_code=201)
async def create_item(item: ItemCreate):
    """Cria um novo item."""
    return {"id": 1, **item.model_dump()}
'''

API_MODELS_INIT = '''"""Models da API."""

from dataclasses import dataclass
from typing import Optional


@dataclass
class Item:
    id: int
    name: str
    description: Optional[str] = None
'''


# =============================================================================
# TEMPLATES CLI
# =============================================================================

CLI_MAIN_PY = '''"""CLI principal."""

import click
from {project_name}.commands import hello, greet


@click.group()
@click.version_option(version='0.1.0')
def cli():
    """Descricao do seu CLI."""
    pass


cli.add_command(hello)
cli.add_command(greet)


def main():
    cli()


if __name__ == '__main__':
    main()
'''

CLI_COMMANDS_INIT = '''"""Comandos do CLI."""

from .hello import hello
from .greet import greet

__all__ = ['hello', 'greet']
'''

CLI_HELLO_CMD = '''"""Comando hello."""

import click


@click.command()
def hello():
    """Exibe uma mensagem de boas-vindas."""
    click.echo("Hello, World!")
'''

CLI_GREET_CMD = '''"""Comando greet."""

import click


@click.command()
@click.argument('name')
@click.option('-c', '--caps', is_flag=True, help='Saida em maiusculas')
def greet(name, caps):
    """Cumprimenta o usuario pelo nome.

    NAME: Nome do usuario
    """
    message = f"Ola, {name}!"
    if caps:
        message = message.upper()
    click.echo(message)
'''

CLI_SETUP_PY = '''"""Setup do pacote."""

from setuptools import setup, find_packages

setup(
    name='{project_name}',
    version='0.1.0',
    packages=find_packages(),
    install_requires=[
        'click>=8.0.0',
    ],
    entry_points={{
        'console_scripts': [
            '{project_name}={project_name}.main:main',
        ],
    }},
)
'''

CLI_PYPROJECT = '''[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "{project_name}"
version = "0.1.0"
description = "Descricao do seu CLI"
requires-python = ">=3.8"
dependencies = [
    "click>=8.0.0",
]

[project.scripts]
{project_name} = "{project_name}.main:main"
'''


# =============================================================================
# TEMPLATES CLEAN ARCHITECTURE
# =============================================================================

CLEAN_MAIN_PY = '''"""Ponto de entrada da aplicacao."""

from src.frameworks.web.app import create_app

app = create_app()

if __name__ == "__main__":
    app.run(debug=True)
'''

CLEAN_ENTITY = '''"""Entidades do dominio."""

from dataclasses import dataclass
from typing import Optional


@dataclass
class User:
    """Entidade User."""
    id: Optional[int] = None
    name: str = ""
    email: str = ""

    def is_valid(self) -> bool:
        """Valida a entidade."""
        return bool(self.name and self.email)
'''

CLEAN_USE_CASE = '''"""Casos de uso da aplicacao."""

from abc import ABC, abstractmethod
from typing import Optional
from src.entities.user import User


class UserRepositoryInterface(ABC):
    """Interface do repositorio de usuarios."""

    @abstractmethod
    def get_by_id(self, user_id: int) -> Optional[User]:
        pass

    @abstractmethod
    def save(self, user: User) -> User:
        pass


class CreateUserUseCase:
    """Caso de uso: criar usuario."""

    def __init__(self, repository: UserRepositoryInterface):
        self.repository = repository

    def execute(self, name: str, email: str) -> User:
        """Executa o caso de uso."""
        user = User(name=name, email=email)

        if not user.is_valid():
            raise ValueError("Dados do usuario invalidos")

        return self.repository.save(user)


class GetUserUseCase:
    """Caso de uso: buscar usuario."""

    def __init__(self, repository: UserRepositoryInterface):
        self.repository = repository

    def execute(self, user_id: int) -> Optional[User]:
        """Executa o caso de uso."""
        return self.repository.get_by_id(user_id)
'''

CLEAN_ADAPTER_REPO = '''"""Implementacao do repositorio."""

from typing import Optional, Dict
from src.entities.user import User
from src.use_cases.user import UserRepositoryInterface


class InMemoryUserRepository(UserRepositoryInterface):
    """Repositorio em memoria (para desenvolvimento/testes)."""

    def __init__(self):
        self._users: Dict[int, User] = {}
        self._next_id = 1

    def get_by_id(self, user_id: int) -> Optional[User]:
        return self._users.get(user_id)

    def save(self, user: User) -> User:
        if user.id is None:
            user.id = self._next_id
            self._next_id += 1
        self._users[user.id] = user
        return user
'''

CLEAN_ADAPTER_PRESENTER = '''"""Presenters para formatacao de saida."""

from dataclasses import dataclass
from typing import Optional
from src.entities.user import User


@dataclass
class UserViewModel:
    """View model do usuario."""
    id: int
    name: str
    email: str


class UserPresenter:
    """Presenter de usuario."""

    @staticmethod
    def to_view_model(user: Optional[User]) -> Optional[UserViewModel]:
        if user is None:
            return None
        return UserViewModel(
            id=user.id,
            name=user.name,
            email=user.email,
        )

    @staticmethod
    def to_dict(user: Optional[User]) -> Optional[dict]:
        if user is None:
            return None
        return {
            "id": user.id,
            "name": user.name,
            "email": user.email,
        }
'''

CLEAN_FRAMEWORK_WEB_FLASK = '''"""Framework web (Flask)."""

from flask import Flask, jsonify, request
from src.use_cases.user import CreateUserUseCase, GetUserUseCase
from src.adapters.repositories.user_repository import InMemoryUserRepository
from src.adapters.presenters.user_presenter import UserPresenter


def create_app() -> Flask:
    """Cria a aplicacao Flask."""
    app = Flask(__name__)

    # Dependency injection
    user_repo = InMemoryUserRepository()
    create_user = CreateUserUseCase(user_repo)
    get_user = GetUserUseCase(user_repo)
    presenter = UserPresenter()

    @app.route('/api/health')
    def health():
        return jsonify({"status": "ok"})

    @app.route('/api/users', methods=['POST'])
    def create_user_endpoint():
        data = request.get_json()
        user = create_user.execute(data['name'], data['email'])
        return jsonify(presenter.to_dict(user)), 201

    @app.route('/api/users/<int:user_id>')
    def get_user_endpoint(user_id):
        user = get_user.execute(user_id)
        if user is None:
            return jsonify({"error": "User not found"}), 404
        return jsonify(presenter.to_dict(user))

    return app
'''

CLEAN_FRAMEWORK_WEB_FASTAPI = '''"""Framework web (FastAPI)."""

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from src.use_cases.user import CreateUserUseCase, GetUserUseCase
from src.adapters.repositories.user_repository import InMemoryUserRepository
from src.adapters.presenters.user_presenter import UserPresenter


class UserCreateRequest(BaseModel):
    name: str
    email: str


# Dependency injection
user_repo = InMemoryUserRepository()
create_user_uc = CreateUserUseCase(user_repo)
get_user_uc = GetUserUseCase(user_repo)
presenter = UserPresenter()


def create_app() -> FastAPI:
    """Cria a aplicacao FastAPI."""
    app = FastAPI(title="Clean Architecture API", version="1.0.0")

    @app.get("/api/health")
    async def health():
        return {"status": "ok"}

    @app.post("/api/users", status_code=201)
    async def create_user_endpoint(data: UserCreateRequest):
        user = create_user_uc.execute(data.name, data.email)
        return presenter.to_dict(user)

    @app.get("/api/users/{user_id}")
    async def get_user_endpoint(user_id: int):
        user = get_user_uc.execute(user_id)
        if user is None:
            raise HTTPException(status_code=404, detail="User not found")
        return presenter.to_dict(user)

    return app
'''

CLEAN_MAIN_FASTAPI = '''"""Ponto de entrada da aplicacao."""

import uvicorn
from src.frameworks.web.app import create_app

app = create_app()

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
'''

CLEAN_TEST_USE_CASE = '''"""Testes dos casos de uso."""

import pytest
from src.entities.user import User
from src.use_cases.user import CreateUserUseCase, GetUserUseCase
from src.adapters.repositories.user_repository import InMemoryUserRepository


@pytest.fixture
def repository():
    return InMemoryUserRepository()


def test_create_user(repository):
    use_case = CreateUserUseCase(repository)
    user = use_case.execute("John", "john@example.com")

    assert user.id is not None
    assert user.name == "John"
    assert user.email == "john@example.com"


def test_get_user(repository):
    # Arrange
    create_use_case = CreateUserUseCase(repository)
    created_user = create_use_case.execute("John", "john@example.com")

    # Act
    get_use_case = GetUserUseCase(repository)
    found_user = get_use_case.execute(created_user.id)

    # Assert
    assert found_user is not None
    assert found_user.name == "John"


def test_create_user_invalid():
    repository = InMemoryUserRepository()
    use_case = CreateUserUseCase(repository)

    with pytest.raises(ValueError):
        use_case.execute("", "")
'''


# =============================================================================
# FUNCOES DE CRIACAO
# =============================================================================

def _create_dirs_and_files(project_path, directories, files, verbose=False):
    """Helper para criar diretorios e arquivos."""
    project_path = Path(project_path)

    for dir_name in directories:
        dir_path = project_path / dir_name
        dir_path.mkdir(parents=True, exist_ok=True)
        if verbose:
            print_creating('dir', dir_name)

    for file_name, content in files.items():
        file_path = project_path / file_name
        file_path.write_text(content, encoding='utf-8')
        if verbose:
            print_creating('file', file_name)


def create_mvc_structure(project_path, project_type, verbose=False):
    """Cria a estrutura de pastas MVC para um projeto."""
    project_path = Path(project_path)

    directories = [
        'app',
        'app/models',
        'app/views',
        'app/controllers',
        'app/static',
        'app/static/css',
        'app/static/js',
        'app/static/img',
        'app/templates',
        'config',
        'tests',
    ]

    if project_type == 'web-flask':
        directories.extend(['.github', '.github/workflows'])
        files = {
            'app/__init__.py': FLASK_APP_INIT,
            'app/models/__init__.py': '"""Models da aplicacao."""\n',
            'app/views/__init__.py': '"""Views da aplicacao."""\n',
            'app/controllers/__init__.py': FLASK_CONTROLLER,
            'app/static/css/style.css': FLASK_CSS,
            'app/static/js/main.js': FLASK_JS,
            'app/templates/base.html': FLASK_BASE_TEMPLATE,
            'config/__init__.py': CONFIG_INIT,
            'config/logging.py': LOGGING_CONFIG,
            'tests/__init__.py': TESTS_INIT,
            'tests/test_app.py': TEST_FLASK_MVC,
            'main.py': FLASK_MAIN_PY,
            '.gitignore': GITIGNORE_CONTENT,
            '.env.example': ENV_EXAMPLE,
            'requirements-dev.txt': REQUIREMENTS_DEV,
            'pyproject.toml': PYTEST_CONFIG,
            '.github/workflows/test.yml': GITHUB_WORKFLOW_TEST,
            'README.md': f'# {project_path.name}\n\nProjeto Flask MVC criado com Prozees.\n\n## Setup\n\n```bash\npip install -r requirements.txt\ncp .env.example .env\n```\n\n## Rodar\n\n```bash\npython main.py\n```\n\n## Testes\n\n```bash\npytest\n```\n',
        }
    elif project_type == 'web-fastapi':
        directories.extend(['.github', '.github/workflows'])
        files = {
            'app/__init__.py': FASTAPI_APP_INIT,
            'app/models/__init__.py': '"""Models da aplicacao."""\n',
            'app/views/__init__.py': '"""Views da aplicacao."""\n',
            'app/controllers/__init__.py': FASTAPI_CONTROLLER,
            'app/static/css/style.css': FLASK_CSS,
            'app/static/js/main.js': FLASK_JS,
            'app/templates/base.html': FASTAPI_BASE_TEMPLATE,
            'config/__init__.py': CONFIG_INIT,
            'config/logging.py': LOGGING_CONFIG,
            'tests/__init__.py': TESTS_INIT,
            'tests/test_app.py': TEST_FASTAPI_MVC,
            'main.py': FASTAPI_MAIN_PY,
            '.gitignore': GITIGNORE_CONTENT,
            '.env.example': ENV_EXAMPLE,
            'requirements-dev.txt': REQUIREMENTS_DEV,
            'pyproject.toml': PYTEST_CONFIG,
            '.github/workflows/test.yml': GITHUB_WORKFLOW_TEST,
            'README.md': f'# {project_path.name}\n\nProjeto FastAPI MVC criado com Prozees.\n\n## Setup\n\n```bash\npip install -r requirements.txt\ncp .env.example .env\n```\n\n## Rodar\n\n```bash\nuvicorn main:app --reload\n```\n\n## Testes\n\n```bash\npytest\n```\n\n## Docs\n\nAcesse http://localhost:8000/docs para ver a documentação interativa.\n',
        }
    else:
        files = {}

    _create_dirs_and_files(project_path, directories, files, verbose)

    if verbose:
        print_success(t('structure_mvc_created'))

    return True


def create_api_structure(project_path, project_type, verbose=False):
    """Create REST API structure."""
    project_path = Path(project_path)

    directories = [
        'app',
        'app/models',
        'app/routes',
        'config',
        'tests',
    ]

    if project_type == 'api-flask':
        directories.extend(['.github', '.github/workflows'])
        files = {
            'app/__init__.py': '"""Pacote da aplicacao."""\n',
            'app/models/__init__.py': API_MODELS_INIT,
            'app/routes/__init__.py': FLASK_API_ROUTES,
            'config/__init__.py': CONFIG_INIT,
            'config/logging.py': LOGGING_CONFIG,
            'tests/__init__.py': TESTS_INIT,
            'tests/test_api.py': TEST_FLASK_API,
            'main.py': FLASK_API_MAIN,
            '.gitignore': GITIGNORE_CONTENT,
            '.env.example': ENV_EXAMPLE,
            'requirements-dev.txt': REQUIREMENTS_DEV,
            'pyproject.toml': PYTEST_CONFIG,
            '.github/workflows/test.yml': GITHUB_WORKFLOW_TEST,
            'README.md': f'# {project_path.name}\n\nAPI REST Flask criada com Prozees.\n\n## Setup\n\n```bash\npip install -r requirements.txt\ncp .env.example .env\n```\n\n## Rodar\n\n```bash\npython main.py\n```\n\n## Testes\n\n```bash\npytest\n```\n',
        }
    elif project_type == 'api-fastapi':
        directories.extend(['.github', '.github/workflows'])
        files = {
            'app/__init__.py': '"""Pacote da aplicacao."""\n',
            'app/models/__init__.py': API_MODELS_INIT,
            'app/routes/__init__.py': FASTAPI_API_ROUTES,
            'config/__init__.py': CONFIG_INIT,
            'config/logging.py': LOGGING_CONFIG,
            'tests/__init__.py': TESTS_INIT,
            'tests/test_api.py': TEST_FASTAPI_API,
            'main.py': FASTAPI_API_MAIN,
            '.gitignore': GITIGNORE_CONTENT,
            '.env.example': ENV_EXAMPLE,
            'requirements-dev.txt': REQUIREMENTS_DEV,
            'pyproject.toml': PYTEST_CONFIG,
            '.github/workflows/test.yml': GITHUB_WORKFLOW_TEST,
            'README.md': f'# {project_path.name}\n\nAPI REST FastAPI criada com Prozees.\n\n## Setup\n\n```bash\npip install -r requirements.txt\ncp .env.example .env\n```\n\n## Rodar\n\n```bash\nuvicorn main:app --reload\n```\n\n## Testes\n\n```bash\npytest\n```\n\n## Docs\n\nAcesse http://localhost:8000/docs\n',
        }
    else:
        files = {}

    _create_dirs_and_files(project_path, directories, files, verbose)

    if verbose:
        print_success(t('structure_api_created'))

    return True


def create_cli_structure(project_path, verbose=False):
    """Create CLI project structure."""
    project_path = Path(project_path)
    project_name = project_path.name

    directories = [
        project_name,
        f'{project_name}/commands',
        'tests',
    ]

    directories.extend(['.github', '.github/workflows'])

    files = {
        f'{project_name}/__init__.py': '"""Pacote principal."""\n',
        f'{project_name}/main.py': CLI_MAIN_PY.replace('{project_name}', project_name),
        f'{project_name}/commands/__init__.py': CLI_COMMANDS_INIT,
        f'{project_name}/commands/hello.py': CLI_HELLO_CMD,
        f'{project_name}/commands/greet.py': CLI_GREET_CMD,
        'tests/__init__.py': TESTS_INIT,
        'tests/test_cli.py': TEST_CLI.replace('{project_name}', project_name),
        'setup.py': CLI_SETUP_PY.replace('{project_name}', project_name),
        'pyproject.toml': CLI_PYPROJECT.replace('{project_name}', project_name) + '\n\n' + PYTEST_CONFIG,
        '.gitignore': GITIGNORE_CONTENT,
        '.env.example': ENV_EXAMPLE,
        'requirements-dev.txt': REQUIREMENTS_DEV,
        '.github/workflows/test.yml': GITHUB_WORKFLOW_TEST,
        'README.md': f'# {project_name}\n\nCLI criado com Prozees.\n\n## Setup\n\n```bash\npip install -e .\ncp .env.example .env\n```\n\n## Uso\n\n```bash\n{project_name} --help\n{project_name} hello\n{project_name} greet Mundo\n```\n\n## Testes\n\n```bash\npytest\n```\n',
    }

    _create_dirs_and_files(project_path, directories, files, verbose)

    if verbose:
        print_success(t('structure_cli_created'))

    return True


def create_clean_structure(project_path, project_type, verbose=False):
    """Create Clean Architecture structure."""
    project_path = Path(project_path)

    directories = [
        'src',
        'src/entities',
        'src/use_cases',
        'src/adapters',
        'src/adapters/repositories',
        'src/adapters/presenters',
        'src/frameworks',
        'src/frameworks/web',
        'config',
        'tests',
        'tests/unit',
        'tests/integration',
        '.github',
        '.github/workflows',
    ]

    # Escolhe o template correto baseado no tipo
    if project_type == 'clean-fastapi':
        web_app_template = CLEAN_FRAMEWORK_WEB_FASTAPI
        main_template = CLEAN_MAIN_FASTAPI
    else:
        web_app_template = CLEAN_FRAMEWORK_WEB_FLASK
        main_template = CLEAN_MAIN_PY

    files = {
        'src/__init__.py': '"""Codigo fonte."""\n',
        'src/entities/__init__.py': '"""Entidades do dominio."""\n',
        'src/entities/user.py': CLEAN_ENTITY,
        'src/use_cases/__init__.py': '"""Casos de uso."""\n',
        'src/use_cases/user.py': CLEAN_USE_CASE,
        'src/adapters/__init__.py': '"""Adapters."""\n',
        'src/adapters/repositories/__init__.py': '"""Repositorios."""\n',
        'src/adapters/repositories/user_repository.py': CLEAN_ADAPTER_REPO,
        'src/adapters/presenters/__init__.py': '"""Presenters."""\n',
        'src/adapters/presenters/user_presenter.py': CLEAN_ADAPTER_PRESENTER,
        'src/frameworks/__init__.py': '"""Frameworks externos."""\n',
        'src/frameworks/web/__init__.py': '"""Framework web."""\n',
        'src/frameworks/web/app.py': web_app_template,
        'config/__init__.py': CONFIG_INIT,
        'config/logging.py': LOGGING_CONFIG,
        'tests/__init__.py': TESTS_INIT,
        'tests/unit/__init__.py': '"""Testes unitarios."""\n',
        'tests/unit/test_use_cases.py': CLEAN_TEST_USE_CASE,
        'tests/integration/__init__.py': '"""Testes de integracao."""\n',
        'main.py': main_template,
        '.gitignore': GITIGNORE_CONTENT,
        '.env.example': ENV_EXAMPLE,
        'requirements-dev.txt': REQUIREMENTS_DEV,
        'pyproject.toml': PYTEST_CONFIG,
        '.github/workflows/test.yml': GITHUB_WORKFLOW_TEST,
        'README.md': f'# {project_path.name}\n\nProjeto com Clean Architecture criado com Prozees.\n\n## Estrutura\n\n```\nsrc/\n  entities/      # Entidades do dominio\n  use_cases/     # Casos de uso (regras de negocio)\n  adapters/      # Adaptadores (repositories, presenters)\n  frameworks/    # Frameworks externos (web, db)\n```\n\n## Setup\n\n```bash\npip install -r requirements.txt\ncp .env.example .env\n```\n\n## Rodar\n\n```bash\npython main.py\n```\n\n## Testes\n\n```bash\npytest\n```\n',
    }

    _create_dirs_and_files(project_path, directories, files, verbose)

    if verbose:
        print_success(t('structure_clean_created'))

    return True
