"""Novel writing pipeline for automated drafting and finalizing."""

from pathlib import Path
from typing import Tuple


class NovelPipeline:
    """Novel auto-writing pipeline."""

    def __init__(self, cwd: Path | None = None):
        self.cwd = cwd or Path.cwd()
        self.theme_file = self.cwd / "小说" / "主题与基调.md"
        self.outline_file = self.cwd / "大纲" / "整体大纲.md"
        self.info_dir = self.cwd / "现有信息"
        self.draft_dir = self.cwd / "草稿"
        self.final_dir = self.cwd / "正文"

    def check_prerequisites(self) -> Tuple[bool, str]:
        """
        Check if prerequisite stages are complete.

        Returns:
            (is_complete, message): Whether complete and status message.
        """
        missing = []

        # Check theme
        if not self.theme_file.exists():
            missing.append("- 主题与基调 (运行 /theme)")

        # Check outline
        if not self.outline_file.exists():
            missing.append("- 大纲 (运行 /outline)")

        # Check initialization
        if not self.info_dir.exists() or not any(self.info_dir.iterdir()):
            missing.append("- 项目初始化 (运行 /init)")

        if missing:
            message = "前置阶段未完成，请先完成以下步骤:\n\n" + "\n".join(missing)
            return False, message

        return True, "前置阶段检查通过"

    def count_chapters(self) -> Tuple[int, int]:
        """
        Count draft and final chapters.

        Returns:
            (draft_count, final_count): Number of drafts and finals.
        """
        draft_count = 0
        final_count = 0

        # Count drafts
        if self.draft_dir.exists():
            draft_files = list(self.draft_dir.glob("[0-9]*.md"))
            draft_count = len(draft_files)

        # Count finals
        if self.final_dir.exists():
            final_files = list(self.final_dir.glob("[0-9]*.md"))
            final_count = len(final_files)

        return draft_count, final_count

    def get_next_action(self) -> Tuple[str, int]:
        """
        Determine the next action based on current state.

        Returns:
            (action, chapter_num): Action type and chapter number.
        """
        draft_count, final_count = self.count_chapters()

        # If drafts are less than final + 4, write draft first
        if draft_count < final_count + 4:
            return "draft", draft_count + 1

        # Otherwise finalize
        return "finalize", final_count + 1

    def is_novel_project(self) -> bool:
        """Check if current directory is a novel project."""
        # Check for at least some novel-related directories
        novel_indicators = [
            self.cwd / ".claude",
            self.cwd / "小说",
            self.cwd / "大纲",
            self.cwd / "草稿",
            self.cwd / "正文",
        ]
        return any(p.exists() for p in novel_indicators)
