"""Exact-term, effective-date retrieval for an original tiny glossary."""
from __future__ import annotations
import hashlib
import json
from datetime import date
from pathlib import Path

ROOT=Path(__file__).resolve().parent


def documents():return json.loads((ROOT/'glossary.json').read_text(encoding='utf-8'))


def active(document,as_of):
    date.fromisoformat(as_of)
    return (document['approved'] is True and document['effective_from']<=as_of and
            (document['effective_until'] is None or as_of<document['effective_until']))


def retrieve(term,as_of='2026-01-31'):
    term=' '.join(term.lower().split())
    matches=[d for d in documents() if active(d,as_of) and
             term in [' '.join(t.lower().split()) for t in [d['term'],*d['aliases']]]]
    if len(matches)!=1:
        return {'status':'needs_clarification','matches':len(matches),'documents':[]}
    document=matches[0]
    digest=hashlib.sha256(json.dumps(document,sort_keys=True,separators=(',',':')).encode()).hexdigest()
    return {'status':'found','documents':[document],'document_sha256':digest,
            'calculated_value':None,'limits':'Definition evidence only; no arithmetic or unrestricted document retrieval.'}


def check_citation(document_id,metric_id,as_of='2026-01-31'):
    matches=[d for d in documents() if d['document_id']==document_id]
    issues=[]
    if len(matches)!=1:issues.append('unknown_or_ambiguous_document')
    else:
        d=matches[0]
        if not active(d,as_of):issues.append('unapproved_or_outside_effective_period')
        if d['metric_id']!=metric_id:issues.append('metric_mismatch')
    return {'metadata_checks_passed':not issues,'issues':issues,
            'semantic_support_review_required':True,'proves_calculated_number':False}
