"""Archive weak proactive topic links into scoped wiki paths."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from niannian.chat.proactive_scope import ProactiveScope


def wiki_archive_path(scope: ProactiveScope, topic: str, *, weak_fill: bool = False) -> Path:
    """Build wiki path under scope namespace, e.g. mode/companion/夏天/能做的事情.md."""
    slug = topic.strip().replace(" ", "_") or "topic"
    base = Path("wiki") / scope.wiki_namespace.replace("/", "/")
    if weak_fill:
        return base / slug / "归档补全.md"
    return base / slug / "能做的事情.md"


def should_archive_weak(confidence: float, *, threshold: float = 0.35) -> bool:
    return confidence < threshold


def build_archive_markdown(*, topic: str, lines: tuple[str, ...]) -> str:
    body = "\n".join(f"- {line}" for line in lines if line.strip())
    return f"# {topic} · 能做的事情\n\n{body}\n"


def archive_weak_topic(
    scope: ProactiveScope,
    *,
    topic: str,
    lines: tuple[str, ...],
    home: Path,
) -> Path:
    """Write archive md under home/wiki/{namespace}/…"""
    rel = wiki_archive_path(scope, topic, weak_fill=True)
    path = home / rel
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(build_archive_markdown(topic=topic, lines=lines), encoding="utf-8")
    return path
