"""Generate a Markdown FAQ document from LLM-generated Q&A pairs.

When running in LLM mode the ``LLMContentEnhancer`` populates
``kg.llm_faq`` with a list of ``{"q": ..., "a": ...}`` dicts.  This
generator renders them into a clean, readable Markdown file.

In basic (non-LLM) mode the generator falls back to a small set of
auto-inferred questions derived from the README structure.
"""

from __future__ import annotations

from datetime import datetime
from pathlib import Path

from ..core.knowledge_graph import EntityType
from ..core.models import (
    CodeBlock,
    DocumentModel,
    GenerationResult,
    ListBlock,
    OutputFormat,
    ParagraphBlock,
)
from .base import BaseGenerator


class FaqGenerator(BaseGenerator):
    """DocumentModel → Markdown FAQ."""

    format = OutputFormat.FAQ

    # ------------------------------------------------------------------
    # Public API
    # ------------------------------------------------------------------

    def generate(self, doc: DocumentModel, output_dir: Path) -> GenerationResult:
        filename = self._safe_filename(doc.metadata.repo_name or "project", "md")
        filename = f"faq_{filename}"
        output_path = self._ensure_dir(output_dir) / filename

        try:
            content = self._build_faq(doc)
            output_path.write_text(content, encoding="utf-8")
            return GenerationResult(format=self.format, output_path=output_path)
        except Exception as exc:
            return GenerationResult(
                format=self.format,
                output_path=output_path,
                success=False,
                error=str(exc),
            )

    # ------------------------------------------------------------------
    # Builder
    # ------------------------------------------------------------------

    def _build_faq(self, doc: DocumentModel) -> str:
        lines: list[str] = []
        name = doc.metadata.repo_name or "This Project"
        now = datetime.now().strftime("%B %d, %Y")
        url = doc.metadata.repo_url or ""

        lines.append(f"# {name} — Frequently Asked Questions")
        lines.append("")
        if doc.metadata.description:
            lines.append(f"> {self._strip_html(doc.metadata.description[:200])}")
            lines.append("")

        # Prefer LLM-generated FAQ
        faq_items = (self.kg.llm_faq if self.kg else None) or []

        if not faq_items:
            # Fallback: deterministic FAQ from README structure
            faq_items = self._infer_faq(doc)

        if not faq_items:
            lines.append("*No FAQ items could be generated for this project.*")
            return "\n".join(lines)

        # TOC
        lines.append("## Contents")
        lines.append("")
        for i, item in enumerate(faq_items, 1):
            q = item.get("q", "")
            anchor = f"q{i}"
            lines.append(f"{i}. [{q}](#{anchor})")
        lines.append("")

        # Q&A
        lines.append("---")
        lines.append("")
        for i, item in enumerate(faq_items, 1):
            q = item.get("q", "")
            a = item.get("a", "")
            lines.append(f"### <a id=\"q{i}\"></a>{i}. {q}")
            lines.append("")
            lines.append(a)
            lines.append("")

        # Footer
        lines.append("---")
        lines.append("")
        if url:
            lines.append(f"For more details see the [{name} README]({url}).")
            lines.append("")
        lines.append(
            f"*Auto-generated by [opendocs](https://pypi.org/project/opendocs/) on {now}.*"
        )
        lines.append("")

        return "\n".join(lines)

    # ------------------------------------------------------------------
    # Deterministic fallback
    # ------------------------------------------------------------------

    def _infer_faq(self, doc: DocumentModel) -> list[dict[str, str]]:
        """Build a basic FAQ from README structure when no LLM is available."""
        name = doc.metadata.repo_name or "this project"
        items: list[dict[str, str]] = []

        # Q1: What is it?
        desc = doc.metadata.description or ""
        first_para = ""
        for b in doc.all_blocks:
            if isinstance(b, ParagraphBlock) and len(b.text) > 30:
                first_para = self._strip_html(b.text[:300])
                break
        answer = desc or first_para or f"{name} is an open-source project."
        items.append({
            "q": f"What is {name}?",
            "a": answer,
        })

        # Q2: How to install?
        install_cmd = ""
        install_kw = ("pip install", "npm install", "cargo install",
                       "brew install", "go install", "docker pull")
        for b in doc.all_blocks:
            if isinstance(b, CodeBlock):
                lower = b.code.lower()
                if any(kw in lower for kw in install_kw):
                    install_cmd = b.code.strip()
                    break
        if install_cmd:
            items.append({
                "q": f"How do I install {name}?",
                "a": f"You can install it with:\n\n```\n{install_cmd}\n```",
            })

        # Q3: Tech stack?
        if self.kg:
            techs = [
                e.name for e in self.kg.entities
                if e.entity_type in (
                    EntityType.TECHNOLOGY, EntityType.FRAMEWORK,
                    EntityType.LANGUAGE,
                )
            ]
            if techs:
                items.append({
                    "q": f"What technologies does {name} use?",
                    "a": f"{name} is built with: {', '.join(techs[:10])}.",
                })

        # Q4: Key features?
        features: list[str] = []
        for sec in doc.sections:
            if "feature" in sec.title.lower():
                for b in sec.blocks:
                    if isinstance(b, ListBlock):
                        features.extend(b.items[:8])
                break
        if features:
            feat_md = "\n".join(f"- {f}" for f in features[:8])
            items.append({
                "q": f"What are the key features of {name}?",
                "a": f"Key features include:\n\n{feat_md}",
            })

        # Q5: Prerequisites?
        if self.kg:
            prereqs = [
                e.name for e in self.kg.entities
                if e.entity_type == EntityType.PREREQUISITE
            ]
            if prereqs:
                items.append({
                    "q": f"What are the prerequisites for {name}?",
                    "a": f"You'll need: {', '.join(prereqs)}.",
                })

        # Q6: License?
        if self.kg:
            licenses = [
                e.name for e in self.kg.entities
                if e.entity_type == EntityType.LICENSE_TYPE
            ]
            if licenses:
                items.append({
                    "q": f"What license is {name} released under?",
                    "a": f"{name} is released under the {licenses[0]} license.",
                })

        return items
