"""Initialize a new novel project."""

import shutil
from pathlib import Path

import click
from rich.console import Console
from rich.panel import Panel

console = Console()


def get_package_data_dir() -> Path:
    """Get the directory containing package data (commands, skills)."""
    import agent_xs
    package_dir = Path(agent_xs.__file__).parent

    # Check if data is bundled with the package (installed mode)
    if (package_dir / "data" / "commands").exists():
        return package_dir / "data"

    # Check if we're in development mode (running from source)
    # src/agent_xs -> src -> root
    source_root = package_dir.parent.parent
    if (source_root / "commands").exists():
        return source_root

    raise click.ClickException(
        "Cannot find package data (commands/skills). "
        "Please ensure agent-xs is installed correctly."
    )


@click.command()
@click.argument("name")
@click.option(
    "--path",
    "-p",
    type=click.Path(),
    default=".",
    help="Parent directory for the project (default: current directory)",
)
def init_project(name: str, path: str):
    """Initialize a new novel project with NAME.

    Creates a new directory with the Claude Code plugin structure,
    including commands, skills, and project templates.

    If the directory already exists, initializes inside it without
    overwriting existing files.
    """
    parent = Path(path).resolve()
    project_dir = parent / name
    is_existing = project_dir.exists()

    console.print(f"\n[bold blue]Creating novel project:[/] {name}\n")

    # Get package data directory
    try:
        data_dir = get_package_data_dir()
    except click.ClickException:
        raise

    commands_src = data_dir / "commands"
    skills_src = data_dir / "skills"

    if not commands_src.exists():
        raise click.ClickException(f"Commands directory not found at {commands_src}")
    if not skills_src.exists():
        raise click.ClickException(f"Skills directory not found at {skills_src}")

    # Create project structure
    try:
        # Create main project directory (or use existing)
        if is_existing:
            console.print(f"  [yellow]=[/] Using existing directory {project_dir}")
        else:
            project_dir.mkdir(parents=True)
            console.print(f"  [green]+[/] Created {project_dir}")

        # Create .claude directory
        claude_dir = project_dir / ".claude"
        if claude_dir.exists():
            console.print(f"  [yellow]=[/] Using existing {claude_dir.relative_to(parent)}")
        else:
            claude_dir.mkdir()
            console.print(f"  [green]+[/] Created {claude_dir.relative_to(parent)}")
            
        # Create .claude/setting.json if not exist
        setting_path = claude_dir / "settings.json"
        if setting_path.exists():
            console.print(f"  [yellow]=[/] Exists {setting_path.relative_to(parent)}")
        else:
            setting_content = "{}"
            setting_path.write_text(setting_content)
            console.print(f"  [green]+[/] Created {setting_path.relative_to(parent)}")

        # Copy commands to .claude/commands (merge with existing)
        commands_dest = claude_dir / "commands"
        if commands_dest.exists():
            # Merge: copy files that don't exist
            for src_file in commands_src.glob("*"):
                dest_file = commands_dest / src_file.name
                if not dest_file.exists():
                    if src_file.is_dir():
                        shutil.copytree(src_file, dest_file)
                    else:
                        shutil.copy2(src_file, dest_file)
                    console.print(f"  [green]+[/] Added {dest_file.relative_to(parent)}")
            console.print(f"  [yellow]=[/] Merged commands to {commands_dest.relative_to(parent)}")
        else:
            shutil.copytree(commands_src, commands_dest)
            console.print(f"  [green]+[/] Copied commands to {commands_dest.relative_to(parent)}")

        # Copy skills to .claude/skills (merge with existing)
        skills_dest = claude_dir / "skills"
        if skills_dest.exists():
            # Merge: copy directories/files that don't exist
            for src_item in skills_src.glob("*"):
                dest_item = skills_dest / src_item.name
                if not dest_item.exists():
                    if src_item.is_dir():
                        shutil.copytree(src_item, dest_item)
                    else:
                        shutil.copy2(src_item, dest_item)
                    console.print(f"  [green]+[/] Added {dest_item.relative_to(parent)}")
            console.print(f"  [yellow]=[/] Merged skills to {skills_dest.relative_to(parent)}")
        else:
            shutil.copytree(skills_src, skills_dest)
            console.print(f"  [green]+[/] Copied skills to {skills_dest.relative_to(parent)}")

        # Create novel project directories
        novel_dirs = [
            "小说",
            "大纲",
            "现有信息/角色",
            "现有信息/物品",
            "现有信息/场景",
            "现有信息/事件",
            "草稿",
            "正文",
        ]

        for dir_name in novel_dirs:
            dir_path = project_dir / dir_name
            if dir_path.exists():
                console.print(f"  [yellow]=[/] Exists {dir_path.relative_to(parent)}")
            else:
                dir_path.mkdir(parents=True, exist_ok=True)
                console.print(f"  [green]+[/] Created {dir_path.relative_to(parent)}")

        # Create .gitignore (skip if exists)
        gitignore_path = project_dir / ".gitignore"
        if gitignore_path.exists():
            console.print(f"  [yellow]=[/] Exists .gitignore")
        else:
            gitignore_content = """# Python
__pycache__/
*.py[cod]
*$py.class
.venv/
venv/

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

# OS
.DS_Store
Thumbs.db

# Local settings
*.local.md
"""
            gitignore_path.write_text(gitignore_content)
            console.print(f"  [green]+[/] Created .gitignore")

        # Create initial README
        readme_content = f"""# {name}

使用 Agent XS 创建的小说项目。

## 项目结构

```
{name}/
├── .claude/           # Claude Code 插件配置
│   ├── commands/      # 自定义命令
│   └── skills/        # 技能定义
├── 小说/              # 小说主题和基调
├── 大纲/              # 整体大纲和时间线
├── 现有信息/          # 知识库
│   ├── 角色/
│   ├── 物品/
│   ├── 场景/
│   └── 事件/
├── 草稿/              # 章节草稿
└── 正文/              # 定稿章节
```

## 开始创作

1. 运行 `/theme` 设定主题与基调
2. 运行 `/outline` 创建大纲
3. 运行 `/init` 初始化知识库
4. 运行 `/draft` 编写草稿
5. 运行 `/finalize` 定稿

## 工具命令

- `xs status` - 查看项目状态
- `xs serve` - 启动 Web 查看器
- `xs auto` - 自动写作流水线
- `xs info` - 查看/搜索知识库
"""
        readme_path = project_dir / "README.md"
        if readme_path.exists():
            console.print(f"  [yellow]=[/] Exists README.md")
        else:
            readme_path.write_text(readme_content)
            console.print(f"  [green]+[/] Created README.md")

    except Exception as e:
        # Only clean up if we created a new directory
        if not is_existing and project_dir.exists():
            shutil.rmtree(project_dir)
        raise click.ClickException(f"Failed to create project: {e}")

    # Success message
    console.print()
    action_word = "initialized" if is_existing else "created"
    console.print(Panel.fit(
        f"[bold green]Project '{name}' {action_word} successfully![/]\n\n"
        f"Next steps:\n"
        f"  1. [cyan]cd {name}[/]\n"
        f"  2. Open in Claude Code\n"
        f"  3. Run [cyan]/theme[/] to start",
        title="Done",
        border_style="green",
    ))
