# retoor <retoor@molodetz.nl>
from __future__ import annotations

import re

from devplacepy.services.jobs.isslop.analysis.signals import (
    AXIS_ORIGIN,
    AXIS_QUALITY,
    SEVERITY_MEDIUM,
    SEVERITY_WEAK,
    FileContext,
    Signal,
)
from devplacepy.services.jobs.isslop.analysis.signals.textual import EM_DASH_THRESHOLD, LLM_LEXICON_PATTERN, LLM_LEXICON_THRESHOLD

EMOJI_HEADER_PATTERN = re.compile(r"^#{1,4}\s*[\U0001F300-\U0001FAFF✨🚀🤝⭐✅❗]")
BADGE_PATTERN = re.compile(r"!\[[^\]]*\]\([^)]*(?:badge|shields\.io)[^)]*\)")
BOILERPLATE_PHRASES: tuple[str, ...] = (
    "getting started",
    "features",
    "installation",
    "prerequisites",
    "contributing",
    "built with",
    "tech stack",
    "acknowledgments",
    "roadmap",
)
MARKETING_PATTERN = re.compile(
    r"blazingly fast|seamlessly|robust and scalable|cutting[- ]edge|revolutioniz|effortlessly|supercharge|powerful and flexible",
    re.IGNORECASE,
)
NOT_JUST_PATTERN = re.compile(r"it'?s not just \w+[,;.]? it'?s", re.IGNORECASE)

EMOJI_HEADER_THRESHOLD: int = 3
BADGE_THRESHOLD: int = 6
BOILERPLATE_THRESHOLD: int = 5
MARKETING_THRESHOLD: int = 3


def detect_documentation(context: FileContext) -> list[Signal]:
    if context.language != "markdown":
        return []
    findings: list[Signal] = []
    emoji_headers = [number for number, line in enumerate(context.lines, start=1) if EMOJI_HEADER_PATTERN.match(line)]
    if len(emoji_headers) >= EMOJI_HEADER_THRESHOLD:
        findings.append(
            Signal(
                "README_EMOJI_STRUCTURE",
                f"{len(emoji_headers)} emoji-prefixed headers in documentation",
                SEVERITY_MEDIUM,
                AXIS_ORIGIN,
                1.0,
                emoji_headers[0],
                context.lines[emoji_headers[0] - 1].strip(),
            )
        )
    lowered = context.text.lower()
    phrase_hits = sum(1 for phrase in BOILERPLATE_PHRASES if phrase in lowered)
    if phrase_hits >= BOILERPLATE_THRESHOLD and emoji_headers:
        findings.append(
            Signal(
                "README_BOILERPLATE",
                f"Generic AI README structure ({phrase_hits} boilerplate sections with emoji headers)",
                SEVERITY_MEDIUM,
                AXIS_QUALITY,
                1.0,
                1,
                ", ".join(phrase for phrase in BOILERPLATE_PHRASES if phrase in lowered)[:150],
            )
        )
    badges = BADGE_PATTERN.findall(context.text)
    if len(badges) >= BADGE_THRESHOLD:
        findings.append(
            Signal("README_BADGE_STUFFING", f"{len(badges)} badges stacked in documentation", SEVERITY_WEAK, AXIS_QUALITY, 1.0, 1, badges[0][:100])
        )
    marketing_hits = MARKETING_PATTERN.findall(context.text)
    if len(marketing_hits) >= MARKETING_THRESHOLD:
        findings.append(
            Signal("MARKETING_TONE", f"Marketing tone in documentation ({len(marketing_hits)} phrases)", SEVERITY_WEAK, AXIS_QUALITY, 1.0, 1, ", ".join(marketing_hits[:4]))
        )
    lexicon_hits = {str(hit).lower() for hit in LLM_LEXICON_PATTERN.findall(context.text)}
    if len(lexicon_hits) >= LLM_LEXICON_THRESHOLD:
        findings.append(
            Signal(
                "LLM_LEXICON",
                f"{len(lexicon_hits)} distinct LLM signature words in documentation",
                SEVERITY_MEDIUM,
                AXIS_ORIGIN,
                2.0,
                1,
                ", ".join(sorted(lexicon_hits)[:6]),
            )
        )
    em_dashes = context.text.count("\u2014")
    if em_dashes >= EM_DASH_THRESHOLD:
        findings.append(
            Signal(
                "EM_DASH_OVERUSE",
                f"{em_dashes} em dashes in documentation, a strong LLM prose habit",
                SEVERITY_MEDIUM,
                AXIS_ORIGIN,
                1.0,
                1,
                f"{em_dashes} em dashes",
            )
        )
    not_just = NOT_JUST_PATTERN.search(context.text)
    if not_just:
        line = context.text.count("\n", 0, not_just.start()) + 1
        findings.append(
            Signal("AI_PROSE_PATTERN", "Characteristic AI prose construction", SEVERITY_WEAK, AXIS_ORIGIN, 1.0, line, not_just.group(0))
        )
    return findings
