"""
Doc Reader — Reads existing documentation to understand project goals.

Reads README, CONTRIBUTING, existing CLAUDE.md, and other docs to extract:
- Project purpose and description
- Architecture decisions
- Setup instructions
- Development workflows
- Team conventions
"""

from pathlib import Path
from typing import Optional


# Files to read, in priority order
DOC_FILES = [
    "README.md",
    "README.rst",
    "README.txt",
    "README",
    "CONTRIBUTING.md",
    "CONTRIBUTING.rst",
    "ARCHITECTURE.md",
    "ARCHITECTURE.rst",
    "docs/ARCHITECTURE.md",
    "docs/architecture.md",
    "docs/getting-started.md",
    "docs/development.md",
    "docs/DEVELOPMENT.md",
    ".github/CONTRIBUTING.md",
]

# Existing AI context files
AI_CONTEXT_FILES = [
    "CLAUDE.md",
    ".cursorrules",
    ".cursor/rules/project.mdc",
    ".cursor/rules/general.mdc",
    ".github/copilot-instructions.md",
    "AGENTS.md",
    "AI_CONTEXT.md",
]


class DocReader:
    """Reads project documentation files."""

    def __init__(self, project_root: str, max_chars_per_file: int = 3000):
        self.root = Path(project_root)
        self.max_chars = max_chars_per_file

    def read_file(self, path: str) -> Optional[str]:
        """Read a file, returning content or None if not found."""
        full_path = self.root / path
        if full_path.exists() and full_path.is_file():
            try:
                content = full_path.read_text(encoding="utf-8", errors="ignore")
                # Truncate if too long
                if len(content) > self.max_chars:
                    content = content[:self.max_chars] + f"\n... [truncated at {self.max_chars} chars]"
                return content
            except Exception:
                pass
        return None

    def read_all_docs(self) -> dict:
        """Read all documentation files."""
        docs = {}

        for doc_file in DOC_FILES:
            content = self.read_file(doc_file)
            if content:
                docs[doc_file] = content

        return docs

    def read_existing_context_files(self) -> dict:
        """Read existing AI context files (CLAUDE.md, .cursorrules, etc.)."""
        existing = {}

        for ctx_file in AI_CONTEXT_FILES:
            content = self.read_file(ctx_file)
            if content:
                existing[ctx_file] = content

        return existing

    def extract_readme_summary(self) -> str:
        """Extract the first meaningful section of the README."""
        for readme in ["README.md", "README.rst", "README.txt", "README"]:
            content = self.read_file(readme)
            if content:
                # Get first ~500 chars (description section)
                lines = content.split("\n")
                # Skip badges and HTML
                useful_lines = [
                    l for l in lines
                    if l.strip()
                    and not l.strip().startswith("[![")
                    and not l.strip().startswith("<")
                    and not l.strip().startswith("<!--")
                ]
                return "\n".join(useful_lines[:20])

        return ""

    def read_makefile_targets(self) -> list[str]:
        """Extract make targets from Makefile (often reveals dev workflow)."""
        content = self.read_file("Makefile")
        if not content:
            content = self.read_file("justfile")
        if not content:
            return []

        targets = []
        for line in content.split("\n"):
            # Makefile targets: "target_name:" at start of line
            if line and not line.startswith("\t") and not line.startswith("#") and ":" in line:
                target = line.split(":")[0].strip()
                if target and not target.startswith(".") and " " not in target:
                    targets.append(target)

        return targets[:15]

    def analyze(self) -> dict:
        """Full documentation analysis."""
        return {
            "docs": self.read_all_docs(),
            "existing_context_files": self.read_existing_context_files(),
            "readme_summary": self.extract_readme_summary(),
            "make_targets": self.read_makefile_targets(),
        }

    def to_summary(self) -> str:
        """Return a summary of what documentation was found."""
        data = self.analyze()
        lines = []

        if data["docs"]:
            files = list(data["docs"].keys())
            lines.append(f"Documentation: {', '.join(files)}")

        if data["existing_context_files"]:
            files = list(data["existing_context_files"].keys())
            lines.append(f"Existing AI context files: {', '.join(files)}")

        if data["make_targets"]:
            lines.append(f"Make targets: {', '.join(data['make_targets'][:6])}")

        return "\n".join(lines) if lines else "No documentation found"
