"""
Simple project initialization for Daita CLI.
Creates minimal, universal project template like create-react-app.
"""
import os
import yaml
from pathlib import Path
from datetime import datetime
from ..utils import find_project_root

async def initialize_project(project_name=None, project_type='basic', template=None, force=False, verbose=False):
    """Initialize a new Daita project with minimal template."""
    
    # Get project name
    if not project_name:
        project_name = input("Project name: ").strip()
        if not project_name:
            project_name = Path.cwd().name
    
    # Determine project directory
    project_dir = Path.cwd() / project_name
    
    # Check if directory exists
    if project_dir.exists() and not force:
        if any(project_dir.iterdir()):  # Directory not empty
            confirm = input(f"Directory '{project_name}' exists and is not empty. Continue? (y/N): ")
            if confirm.lower() != 'y':
                print(" Initialization cancelled")
                return
    
    # Create project directory
    project_dir.mkdir(exist_ok=True)
    
    print(f" Creating Daita project: {project_name}")
    print(f" Location: {project_dir}")
    
    # Create minimal project structure
    _create_project_structure(project_dir, verbose)
    _create_project_config(project_dir, project_name, verbose)
    _create_starter_files(project_dir, project_name, verbose)
    _create_supporting_files(project_dir, project_name, verbose)
    
    # Import freemium utilities
    try:
        from ..utils import get_freemium_success_message
        print("")
        print(get_freemium_success_message(project_name))
        print("")
        print(" Development setup:")
        print(f"   export OPENAI_API_KEY=your_key_here    # Configure LLM")
        print(f"   pip install -r requirements.txt       # Install dependencies")
        print(f"   python agents/my_agent.py              # Test example agent")
    except ImportError:
        # Fallback to original message if utils not available
        print(f"")
        print(f"Project created successfully")
        print(f"")
        print(f"Get started:")
        print(f"   cd {project_name}")
        print(f"   export OPENAI_API_KEY=your_key_here")
        print(f"   pip install -r requirements.txt")
        print(f"   python agents/my_agent.py          # Test the example agent")
        print(f"   daita create agent new_agent       # Create a new agent")
        print(f"   daita test                         # Test all components")
        print(f"   daita test --watch                 # Watch for changes while developing")

def _create_project_structure(project_dir, verbose):
    """Create minimal directory structure."""
    directories = [
        '.daita',
        'agents',
        'workflows', 
        'data',
        'tests'
    ]
    
    for dir_name in directories:
        dir_path = project_dir / dir_name
        dir_path.mkdir(exist_ok=True)
        
        # Create __init__.py for Python packages
        if dir_name in ['agents', 'workflows', 'tests']:
            init_file = dir_path / '__init__.py'
            init_file.write_text('"""Daita project components."""\n')
        
        if verbose:
            print(f"    Created: {dir_name}/")

def _create_project_config(project_dir, project_name, verbose):
    """Create minimal daita-project.yaml configuration."""
    
    config = {
        'name': project_name,
        'version': '1.0.0',
        'description': f'A Daita AI agent project',
        'created_at': datetime.utcnow().isoformat(),

        # Project components (will be populated as user creates them)
        'agents': [],
        'workflows': []
    }
    
    config_file = project_dir / 'daita-project.yaml'
    with open(config_file, 'w') as f:
        yaml.dump(config, f, default_flow_style=False, sort_keys=False)
    
    if verbose:
        print(f"    Created: daita-project.yaml")

def _create_starter_files(project_dir, project_name, verbose):
    """Create minimal starter agent and workflow files."""
    
    # Simple starter agent
    starter_agent = '''"""
My Agent

A simple starter agent. Replace this with your own logic.
"""
from daita import SubstrateAgent

def create_agent():
    """Create the agent instance using direct SubstrateAgent pattern."""
    # Option 1: Simple instantiation (uses defaults)
    agent = SubstrateAgent(name="My Agent")
    
    # Option 2: Direct LLM configuration (uncomment and modify as needed)
    # import os
    # agent = SubstrateAgent(
    #     name="My Agent",
    #     llm_provider="openai",
    #     model="gpt-4",
    #     api_key=os.getenv("OPENAI_API_KEY")
    # )
    
    # Optional: Add plugins
    # from daita.plugins import postgresql
    # agent.add_plugin(postgresql(host="localhost", database="mydb"))
    
    return agent

if __name__ == "__main__":
    import asyncio
    
    async def main():
        agent = create_agent()
        result = await agent.process("test_task", "Hello, world!")
        print(result)
    
    asyncio.run(main())
'''
    
    # Simple starter workflow
    starter_workflow = '''"""
My Workflow

A simple starter workflow. Replace this with your own logic.
"""
from daita import SubstrateAgent, Workflow

def create_workflow():
    """Create the workflow instance using direct Workflow pattern."""
    workflow = Workflow("My Workflow")
    
    # Add your agents here
    # agent = SubstrateAgent(name="Agent")
    # workflow.add_agent("agent", agent)
    
    return workflow

async def run_workflow(data=None):
    """Run the workflow with direct pattern."""
    workflow = create_workflow()
    
    try:
        await workflow.start()
        
        # Your workflow logic here
        result = f"Workflow processed: {data}"
        
        return {
            'status': 'success',
            'result': result
        }
        
    finally:
        await workflow.stop()

if __name__ == "__main__":
    import asyncio
    
    async def main():
        result = await run_workflow("Hello, workflow!")
        print(result)
    
    asyncio.run(main())
'''
    
    # Write starter files
    (project_dir / 'agents' / 'my_agent.py').write_text(starter_agent)
    (project_dir / 'workflows' / 'my_workflow.py').write_text(starter_workflow)
    
    if verbose:
        print(f"    Created: agents/my_agent.py")
        print(f"    Created: workflows/my_workflow.py")

def _create_supporting_files(project_dir, project_name, verbose):
    """Create supporting files (requirements, README, etc.)."""
    
    # Minimal requirements.txt
    requirements = '''# Daita Agents Framework
daita-agents>=0.1.0

# LLM provider (choose one)
openai>=1.0.0

# Development
pytest>=7.0.0
pytest-asyncio>=0.21.0
'''
    
    # Simple .gitignore
    gitignore = '''# Python
__pycache__/
*.py[cod]
*.so
.Python
build/
dist/
*.egg-info/

# Virtual environments
.env
.venv
venv/

# IDE
.vscode/
.idea/

# OS
.DS_Store

# API keys
.env.local
'''
    
    # README with freemium messaging
    readme = f'''# {project_name}

A Daita AI agent project.

## Quick Setup

1. Install dependencies:
   ```bash
   pip install -r requirements.txt
   ```

2. Set your LLM API key:
   ```bash
   export OPENAI_API_KEY=your_key_here
   ```

## Free Local Development

Build and test your agents locally - completely free:

```bash
# Test the example agent
python agents/my_agent.py

# Test all components
daita test

# Watch for changes while developing
daita test --watch

# Create new components
daita create agent my_new_agent
daita create workflow my_new_workflow
```

## Production Cloud Hosting

Ready to deploy to the cloud? Get 24/7 hosting, monitoring, and insights:

```bash
# Get your API key at daita-tech.io
export DAITA_API_KEY='your-key-here'

# Deploy to cloud
daita push                   # Deploy to production

# Monitor your deployments
daita status                 # Deployment status
daita logs                   # View execution logs
```

## Project Structure

```
{project_name}/
├── agents/          # Your AI agents (free to create & test)
│   └── my_agent.py
├── workflows/       # Your workflows (free to create & test)
│   └── my_workflow.py
├── data/           # Data files
├── tests/          # Tests
└── daita-project.yaml  # Project config
```

## Command Reference

**Free Commands (Local Development):**
- `daita test` - Test all agents and workflows
- `daita test --watch` - Development mode with auto-reload
- `daita create agent <name>` - Create new agent
- `daita create workflow <name>` - Create new workflow

**Premium Commands (Cloud Hosting):**
- `daita push <env>` - Deploy to cloud
- `daita status` - Monitor deployments
- `daita logs <env>` - View execution logs
- `daita run <agent>` - Execute remotely

## Learn More

-  [Get API Key](https://daita-tech.io) - Start your free trial
-  [Documentation](https://docs.daita-tech.io)
'''
    
    # Simple test file
    test_file = '''"""
Basic test for your agents and workflows.
"""
import pytest
import asyncio

# Example test - replace with your own
@pytest.mark.asyncio
async def test_my_agent():
    """Test the example agent."""
    from agents.my_agent import create_agent
    
    agent = create_agent()
    result = await agent.process("test data")
    
    assert result["status"] == "success"
    assert "test data" in result["result"]

@pytest.mark.asyncio  
async def test_my_workflow():
    """Test the example workflow."""
    from workflows.my_workflow import create_workflow
    
    workflow = create_workflow()
    result = await workflow.run("test data")
    
    assert result["status"] == "success"

if __name__ == "__main__":
    # Run tests directly
    asyncio.run(test_my_agent())
    asyncio.run(test_my_workflow())
    print(" All tests passed!")
'''
    
    # Write all supporting files
    (project_dir / 'requirements.txt').write_text(requirements)
    (project_dir / '.gitignore').write_text(gitignore)
    (project_dir / 'README.md').write_text(readme)
    (project_dir / 'tests' / 'test_basic.py').write_text(test_file)
    
    # Create empty data directory with placeholder
    (project_dir / 'data' / '.gitkeep').write_text('')
    
    if verbose:
        print(f"    Created: requirements.txt")
        print(f"    Created: .gitignore")
        print(f"    Created: README.md")
        print(f"    Created: tests/test_basic.py")

