"""
Content domain: public article serving for CMS-generated coffee market pages.
"""
import json
from pathlib import Path

from quart import Blueprint, abort, render_template

from ..core import fetch_one

bp = Blueprint(
    "content",
    __name__,
    template_folder=str(Path(__file__).parent / "templates"),
)


async def _serve_article(url_path: str):
    """Fetch article by url_path and render it with its body template."""
    article = await fetch_one(
        """SELECT a.*, td.data_json, at.body_template
           FROM articles a
           LEFT JOIN template_data td ON td.id = a.template_data_id
           LEFT JOIN article_templates at ON at.id = td.template_id
           WHERE a.url_path = ? AND a.status = 'published'""",
        (url_path,),
    )
    if not article:
        abort(404)

    body_html = ""
    if article.get("body_template") and article.get("data_json"):
        try:
            from jinja2 import BaseLoader, Environment
            data = json.loads(article["data_json"])
            env = Environment(loader=BaseLoader())
            body_html = env.from_string(article["body_template"]).render(**data)
        except Exception:
            body_html = "<p>Content temporarily unavailable.</p>"

    return await render_template(
        "content/article.html",
        article=article,
        body_html=body_html,
    )


@bp.route("/coffee/market/<int:year>")
async def market_year_article(year: int):
    """Serve a CMS article at /coffee/market/<year>."""
    return await _serve_article(f"/coffee/market/{year}")


@bp.route("/coffee/<slug>")
async def country_article(slug: str):
    """Serve a CMS article at /coffee/<country-slug>."""
    return await _serve_article(f"/coffee/{slug}")
