from __future__ import annotations
from pathlib import Path
from core.models import Article
from core.frontmatter import parse_frontmatter

def scan_articles(blog_root: Path) -> list[Article]:
    articles: list[Article] = []
    by_slug: dict[tuple[str, str], Path] = {}

    for lang in ("it", "en"):
        content_dir = blog_root / "content" / lang / "articles"
        if not content_dir.exists():
            continue
        for index_md in sorted(content_dir.glob("*/index.md")):
            slug = index_md.parent.name
            by_slug[(lang, slug)] = index_md

    for (lang, slug), path in by_slug.items():
        other_lang = "en" if lang == "it" else "it"
        translation_path = by_slug.get((other_lang, slug))
        try:
            fm, _ = parse_frontmatter(path)
        except (ValueError, OSError):
            fm = {}
        articles.append(Article(
            slug=slug,
            lang=lang,
            path=path,
            frontmatter=fm,
            has_translation=translation_path is not None,
            translation_path=translation_path,
        ))

    return articles
