"""Review rules, mirrored for the generator's tests. The real checks run on the server
(cloudflare/lib/reviews/rules.mjs and data.mjs), never in the browser.

- A stars-only review can add written text later. Stars stay locked. It is NOT a new review and uses no quota.
  The review shows "Text added <date>". Replacing after 6 calendar months is the only way to change stars (U-25).
- Anonymous replies (N-10, REV-016, REV-049):
    * under your OWN Anonymous review, every reply is Anonymous and locked;
    * if your review of that school is named, all your replies there are named;
    * otherwise (an Anonymous review but someone else's thread, or no review at all) Trial, Pro and Founding
      choose per reply; Free is always named.
  An Anonymous post can never be switched to named (N-20)."""
import datetime as dt

REPLACE_AFTER_MONTHS = 6


def add_text_later(review, text, today):
    if review.get("text"):
        raise ValueError("review already has written text")
    if not text.strip():
        raise ValueError("text is empty")
    out = dict(review)
    out.update(text=text.strip(), text_added_at=today.isoformat())
    return out, {"new_review": False, "quota_used": 0, "label": f"Text added {today.day} {today:%b} {today.year}"}


def change_stars(review, new_stars, today):
    """Stars can't be edited in place after the 15-minute window. Only a full replace after 6 months."""
    if today < replace_from(review):
        raise PermissionError("stars are locked until " + replace_from(review).isoformat())
    return {"replace": True, "new_review": True, "stars": new_stars}


def replace_from(review):
    d = dt.date.fromisoformat(review["published_at"])
    m = d.month - 1 + REPLACE_AFTER_MONTHS
    y, m = d.year + m // 12, m % 12 + 1
    feb = 29 if y % 4 == 0 and (y % 100 or y % 400 == 0) else 28
    return dt.date(y, m, min(d.day, [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1]))


def reply_identity(own_review, wants_anonymous, plan_allows_anonymous, on_own_thread=False):
    """Returns (anonymous, toggle_shown). own_review = the member's own review of this school, or None."""
    if own_review is not None and own_review.get("anonymous") and on_own_thread:
        return True, False                      # locked, even if the plan has since ended (SUG-31)
    if own_review is not None and not own_review.get("anonymous"):
        return False, False                     # named review: named replies
    if not plan_allows_anonymous:
        return False, False
    return bool(wants_anonymous), True
