#!/usr/bin/env python3
from __future__ import annotations

import argparse
import datetime as dt
from pathlib import Path

from build_site import _add_interval, load_manifest, repository_paths
from render import split_frontmatter


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("manifest", type=Path)
    parser.add_argument("--as-of", type=dt.date.fromisoformat, default=dt.date.today())
    args = parser.parse_args()
    manifest_path = args.manifest.resolve()
    manifest = load_manifest(manifest_path)
    repositories = repository_paths(manifest_path, manifest)
    stale = 0
    for document in manifest["documents"]:
        repo = repositories[document["source_repo"]]
        source = (repo / document["source_path"]).resolve()
        meta, _markdown = split_frontmatter(source.read_text(encoding="utf-8"))
        reviewed = meta.get("last_reviewed") or meta.get("updated")
        interval = document.get("review_interval") or meta.get("review_interval")
        if not reviewed or not interval:
            print(f"UNDECLARED {document['id']}: review date/interval missing")
            stale += 1
            continue
        due = _add_interval(reviewed, interval)
        state = "STALE" if due < args.as_of else "current"
        print(f"{state} {document['id']}: reviewed {reviewed}, due {due}")
        stale += state == "STALE"
    return 1 if stale else 0


if __name__ == "__main__":
    raise SystemExit(main())
