"""
项目模板生成器

生成新项目的配置文件和目录结构。
"""

from pathlib import Path


class ProjectTemplate:
    """项目模板生成器"""

    def create_project(
        self,
        target_dir: Path,
        project_name: str,
        llm_provider: str = "openrouter",
        chinese: bool = False,
    ) -> None:
        """
        创建新项目

        Args:
            target_dir: 目标目录
            project_name: 项目名称
            llm_provider: LLM 提供商
            chinese: 是否使用中文上下文
        """
        # 创建目录结构
        target_dir.mkdir(parents=True, exist_ok=True)
        (target_dir / "config").mkdir(exist_ok=True)
        (target_dir / "config" / "prompts").mkdir(exist_ok=True)
        (target_dir / "logs").mkdir(exist_ok=True)

        # 生成文件
        self._write_config(target_dir, llm_provider, chinese)
        self._write_env_example(target_dir, llm_provider)
        self._write_run_script(target_dir)
        self._write_gitignore(target_dir)
        self._write_readme(target_dir, project_name)
        self._write_custom_prompts(target_dir)

    def _write_config(self, target_dir: Path, provider: str, chinese: bool) -> None:
        """生成 agent.yaml 配置文件"""
        # Provider 配置映射
        provider_configs = {
            "anthropic": {
                "provider_class": "ClaudeAnthropicClient",
                "model_name": "claude-sonnet-4-20250514",
                "api_key_env": "ANTHROPIC_API_KEY",
                "extra_config": """    anthropic_api_key: "${oc.env:ANTHROPIC_API_KEY}"
    anthropic_base_url: "${oc.env:ANTHROPIC_BASE_URL,https://api.anthropic.com}"\n""",
            },
            "openai": {
                "provider_class": "GPTOpenAIClient",
                "model_name": "gpt-4o",
                "api_key_env": "OPENAI_API_KEY",
                "extra_config": """    openai_api_key: "${oc.env:OPENAI_API_KEY}"
    openai_base_url: "${oc.env:OPENAI_BASE_URL,https://api.openai.com/v1}"\n""",
            },
            "openrouter": {
                "provider_class": "ClaudeOpenRouterClient",
                "model_name": "anthropic/claude-sonnet-4",
                "api_key_env": "OPENROUTER_API_KEY",
                "extra_config": """    openrouter_api_key: "${oc.env:OPENROUTER_API_KEY}"
    openrouter_base_url: "${oc.env:OPENROUTER_BASE_URL,https://openrouter.ai/api/v1}"
    openrouter_provider: ""\n""",
            },
            "deepseek": {
                "provider_class": "DeepSeekOpenRouterClient",
                "model_name": "deepseek-chat",
                "api_key_env": "DEEPSEEK_API_KEY",
                "extra_config": """    deepseek_api_key: "${oc.env:DEEPSEEK_API_KEY}"
    deepseek_base_url: "${oc.env:DEEPSEEK_BASE_URL,https://api.deepseek.com}"\n""",
            },
        }

        cfg = provider_configs[provider]

        config_content = f"""# Agent Configuration
# Generated by: mem-deep-research init

defaults:
  - override hydra/job_logging: none
  - _self_

main_agent:
  # Prompt 配置
  prompt:
    agent_type: main
    tool_format: xml
    presets: [research]
    # 自定义模板 (可选)
    # templates_dir: "${{oc.env:PROJECT_DIR,''}}/config/prompts"
    # custom_system_template: my_system_prompt
    # custom_summarize_template: my_summarize_prompt

  # LLM 配置
  llm:
    provider_class: "{cfg["provider_class"]}"
    model_name: "{cfg["model_name"]}"
    async_client: true

    # Model parameters
    temperature: 0.3
    top_p: 0.95
    min_p: 0.0
    top_k: -1
    max_tokens: 32000

    # Timeout and retry
    timeout: 1800
    retry_max_attempts: 5
    retry_strategy: "exponential"
    retry_multiplier: 5
    retry_wait_seconds: 10

    # API credentials
{cfg["extra_config"]}
    # Streaming and caching
    enable_streaming: true
    disable_cache_control: false
    keep_tool_result: -1
    oai_tool_thinking: false

  # 工具配置
  # Available tools:
  #   - tool-searching-serper  # Google search via Serper API
  #   - tool-searching         # Alternative search
  #   - tool-reading           # Web page reading/scraping
  #   - tool-code              # Code execution (E2B sandbox)
  #   - tool-reasoning         # Advanced reasoning
  #   - tool-audio             # Audio processing
  #   - tool-image-video       # Image/video processing
  #   - tool-markitdown        # Document conversion
  tool_config:
    - tool-searching-serper
    # - tool-reading  # Requires SUMMARY_LLM_API_KEY

  # 执行限制
  max_turns: 20
  max_tool_calls_per_turn: 10
  keep_tool_result: -1

  # 任务引擎（deep 模式）
  task_engine:
    enabled: true
    reflection_interval: 3
    require_explicit_planning: true

  # 上下文设置
  add_message_id: true
  chinese_context: {str(chinese).lower()}

  # 输入/输出处理 (可选)
  input_process:
    hint_generation: false
    hint_llm_base_url: ""
  output_process:
    final_answer_extraction: false
    final_answer_llm_base_url: ""
    final_answer_model: ""

  # 消息拦截器配置
  interceptor:
    preset: "default"

# 子 Agent 配置 (可选)
sub_agents: null

# 基准测试设置
benchmark:
  name: "custom"

output_dir: logs/
"""
        (target_dir / "config" / "agent.yaml").write_text(config_content)

    def _write_env_example(self, target_dir: Path, provider: str) -> None:
        """生成 .env.example 文件"""
        content = """# ============================================================
# Environment Variables for Deep Research Agent
# ============================================================
# Copy this file to .env and fill in your API keys

# ============================================================
# LLM Provider API Keys
# ============================================================

# OpenRouter (recommended - supports multiple models)
OPENROUTER_API_KEY=your-openrouter-api-key
OPENROUTER_BASE_URL=https://openrouter.ai/api/v1

# Anthropic (Claude direct API)
ANTHROPIC_API_KEY=your-anthropic-api-key
ANTHROPIC_BASE_URL=https://api.anthropic.com

# OpenAI (GPT models)
OPENAI_API_KEY=your-openai-api-key
OPENAI_BASE_URL=https://api.openai.com/v1

# DeepSeek
DEEPSEEK_API_KEY=your-deepseek-api-key
DEEPSEEK_BASE_URL=https://api.deepseek.com

# ============================================================
# Search & Scraping Tools
# ============================================================

# Serper API (Google Search) - Get key at https://serper.dev
SERPER_API_KEY=your-serper-api-key

# Jina AI (Web scraping) - Get key at https://jina.ai
JINA_API_KEY=your-jina-api-key

# ============================================================
# Optional Settings
# ============================================================

# Chinese context (set to true for Chinese output)
CHINESE_CONTEXT=false

# Logging level (DEBUG, INFO, WARNING, ERROR)
LOGGER_LEVEL=INFO
"""
        (target_dir / ".env.example").write_text(content)
        (target_dir / ".env").write_text(content)

    def _write_run_script(self, target_dir: Path) -> None:
        """生成 run.py 脚本"""
        content = '''#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Research Agent Runner

Usage:
    python run.py "Your research task"
    python run.py --test  # Test setup
"""

import argparse
import asyncio
import os
import sys
from pathlib import Path

# 设置项目目录
PROJECT_DIR = Path(__file__).parent.resolve()
os.environ["PROJECT_DIR"] = str(PROJECT_DIR)

# 加载 .env
def load_env():
    env_file = PROJECT_DIR / ".env"
    if env_file.exists():
        with open(env_file) as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#") and "=" in line:
                    key, value = line.split("=", 1)
                    os.environ.setdefault(key.strip(), value.strip())

load_env()


def get_deep_research():
    """Import DeepResearch, with fallback to source if not installed."""
    try:
        from mem_deep_research import DeepResearch
        return DeepResearch
    except ImportError:
        pass

    # Fallback: try to import from source (for development)
    framework_dir = PROJECT_DIR.parent / "mem_deep_research"
    if framework_dir.exists() and (framework_dir / "mem_deep_research_core").exists():
        sys.path.insert(0, str(framework_dir))
        try:
            from mem_deep_research_core.deep_research import DeepResearch
            return DeepResearch
        except ImportError:
            pass

    print("Error: mem-deep-research not installed")
    print("Install with: pip install mem-deep-research")
    sys.exit(1)


async def run_task(task: str):
    """运行研究任务"""
    DeepResearch = get_deep_research()

    dr = DeepResearch.from_project(PROJECT_DIR)

    print(f"\\n{'='*60}")
    print(f"Task: {task}")
    print(f"{'='*60}\\n")

    result = await dr.run(task)

    print(f"\\n{'='*60}")
    print(f"Status: {result.status}")
    print(f"Duration: {result.duration_seconds:.2f}s")
    print(f"{'='*60}")
    print(f"\\nAnswer:\\n{result.answer}")

    if result.log_path:
        print(f"\\nLog: {result.log_path}")

    return result


def test_setup():
    """测试配置"""
    print("=" * 60)
    print("Testing Setup")
    print("=" * 60)

    print(f"\\n[1] Project Directory: {PROJECT_DIR}")

    # 检查配置文件
    config_path = PROJECT_DIR / "config" / "agent.yaml"
    if config_path.exists():
        print(f"[OK] Config file: {config_path}")
    else:
        print(f"[ERROR] Config file not found: {config_path}")
        sys.exit(1)

    # 检查环境变量
    print("\\n[2] Environment Variables:")
    env_vars = ["OPENROUTER_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY", "SERPER_API_KEY"]
    for var in env_vars:
        value = os.environ.get(var, "")
        if value and not value.startswith("your-"):
            print(f"    {var}: ****{value[-4:]}")
        elif value:
            print(f"    {var}: (not set - using placeholder)")
        else:
            print(f"    {var}: (not set)")

    # 测试导入
    print("\\n[3] Testing imports...")
    try:
        DeepResearch = get_deep_research()
        print("    mem_deep_research: OK")
    except SystemExit:
        sys.exit(1)

    # 测试加载配置
    print("\\n[4] Testing config loading...")
    try:
        dr = DeepResearch.from_project(PROJECT_DIR)
        print("    DeepResearch.from_project: OK")
    except Exception as e:
        print(f"    DeepResearch.from_project: FAILED - {e}")
        sys.exit(1)

    print("\\n" + "=" * 60)
    print("All tests passed!")
    print("=" * 60)
    print("\\nTo run the agent:")
    print(\'  python run.py "your research task"\')


def main():
    parser = argparse.ArgumentParser(description="Run research agent")
    parser.add_argument("task", nargs="?", help="Research task")
    parser.add_argument("--test", "-t", action="store_true", help="Test setup")
    args = parser.parse_args()

    if args.test:
        test_setup()
        return

    if not args.task:
        parser.print_help()
        sys.exit(1)

    asyncio.run(run_task(args.task))


if __name__ == "__main__":
    main()
'''
        (target_dir / "run.py").write_text(content)

    def _write_gitignore(self, target_dir: Path) -> None:
        """生成 .gitignore"""
        content = """# Environment
.env
.venv/
venv/

# Logs
logs/
*.log

# Python
__pycache__/
*.py[cod]
*.egg-info/
dist/
build/

# IDE
.idea/
.vscode/
*.swp
"""
        (target_dir / ".gitignore").write_text(content)

    def _write_readme(self, target_dir: Path, project_name: str) -> None:
        """生成 README.md"""
        content = f"""# {project_name}

A deep research agent project powered by [mem-deep-research](https://github.com/ ai/mem-deep-research).

## Quick Start

### 1. Install Framework

```bash
pip install mem-deep-research
```

### 2. Configure API Keys

Edit `.env` file with your API keys:

```bash
# Required: At least one LLM provider
OPENROUTER_API_KEY=your-key    # or
ANTHROPIC_API_KEY=your-key     # or
OPENAI_API_KEY=your-key

# Required: Search API
SERPER_API_KEY=your-serper-key  # Get at https://serper.dev
```

### 3. Test Setup

```bash
python run.py --test
```

### 4. Run Research

```bash
python run.py "Research the latest developments in AI agents"
```

## Usage

### Command Line

```bash
# Basic research
python run.py "What are the latest trends in AI?"

# Chinese output
python run.py "研究一下大语言模型的最新进展"
```

### Python API

```python
import asyncio
from mem_deep_research import DeepResearch

async def main():
    # Load from project directory
    dr = DeepResearch.from_project(".")

    # Run research
    result = await dr.run("Your research task")

    print(f"Status: {{result.status}}")
    print(f"Answer: {{result.answer}}")
    print(f"Duration: {{result.duration_seconds:.2f}}s")

asyncio.run(main())
```

### Sync API

```python
from mem_deep_research import DeepResearch

dr = DeepResearch.from_project(".")
result = dr.run_sync("Your research task")
print(result.answer)
```

## Configuration

### LLM Providers

Edit `config/agent.yaml` to change LLM provider:

```yaml
main_agent:
  llm:
    # OpenRouter (default)
    provider_class: "ClaudeOpenRouterClient"
    model_name: "anthropic/claude-sonnet-4"

    # Or Anthropic direct
    # provider_class: "ClaudeAnthropicClient"
    # model_name: "claude-sonnet-4-20250514"

    # Or OpenAI
    # provider_class: "GPTOpenAIClient"
    # model_name: "gpt-4o"
```

### Available Tools

```yaml
main_agent:
  tool_config:
    - tool-searching-serper  # Google search (Serper API)
    - tool-reading           # Web page reading
    - tool-code              # Code execution (E2B)
    - tool-reasoning         # Advanced reasoning
    - tool-audio             # Audio processing
    - tool-image-video       # Image/video processing
```

### Custom Prompts

Create custom prompt templates in `config/prompts/`:

```yaml
main_agent:
  prompt:
    templates_dir: "${{oc.env:PROJECT_DIR,''}}/config/prompts"
    custom_system_template: my_system_prompt
    custom_summarize_template: my_summarize_prompt
```

## Project Structure

```
{project_name}/
├── config/
│   ├── agent.yaml           # Main configuration
│   └── prompts/             # Custom prompt templates
│       ├── my_system_prompt.md
│       └── my_summarize_prompt.md
├── logs/                    # Task execution logs (JSON)
├── run.py                   # CLI runner script
├── .env                     # API keys (gitignored)
├── .env.example             # Example environment file
├── .gitignore
└── README.md
```

## Troubleshooting

### "API key not found"
Make sure your `.env` file has valid API keys.

### "Tool execution failed"
Check if the required tool dependencies are installed (e.g., `npx` for Serper).

### View Logs
Check `logs/` directory for detailed execution logs in JSON format.

## Links

- [Framework Documentation](https://github.com/cjhyy/mem-deep-research)
- [Serper API](https://serper.dev) - Search API
- [OpenRouter](https://openrouter.ai) - Multi-model API gateway
"""
        (target_dir / "README.md").write_text(content)

    def _write_custom_prompts(self, target_dir: Path) -> None:
        """生成自定义 prompt 模板示例"""
        # 系统 prompt 示例
        system_prompt = """# Custom System Prompt

You are a research assistant specialized in {{domain}}.

Today is: {{date}}. Current time: {{time}}.

## Available Tools
{{mcp_tools}}

## Your Objective
Conduct thorough research on the given topic, using available tools to gather information.
"""
        (target_dir / "config" / "prompts" / "my_system_prompt.md").write_text(system_prompt)

        # 总结 prompt 示例
        summarize_prompt = """# Summary Prompt

Summarize the research findings for the following task:

**Original Task:**
{{task_description}}

## Requirements
- Write in {{target_language}}
- Focus on key findings and insights
- Be concise but comprehensive
"""
        (target_dir / "config" / "prompts" / "my_summarize_prompt.md").write_text(summarize_prompt)
