"""Quick-add parser: turns 'Dentist dec 4 2-3pm' into structured fields.

    parse("Water plants every 3 days when done", today)
    -> {"title": "Water plants", "date": "2026-11-15", "rrule": "FREQ=DAILY;INTERVAL=3",
        "recur_from": "done", ...}
"""
import re
from datetime import date, timedelta

from dateutil.relativedelta import relativedelta

import recurrence

MONTHS = {
    "jan": 1, "january": 1, "feb": 2, "february": 2, "mar": 3, "march": 3,
    "apr": 4, "april": 4, "may": 5, "jun": 6, "june": 6, "jul": 7, "july": 7,
    "aug": 8, "august": 8, "sep": 9, "sept": 9, "september": 9, "oct": 10,
    "october": 10, "nov": 11, "november": 11, "dec": 12, "december": 12,
}
_MONTH_RE = "|".join(sorted(MONTHS, key=len, reverse=True))
_WD_RE = ("monday|mon|tuesday|tues|tue|wednesday|weds|wed|thursday|thurs|thur|thu|"
          "friday|fri|saturday|sat|sunday|sun")
_PREFIX = r"(?:(?:due|by|on|starting|start|from|beginning)\s+)?"
# "am"/"pm" may follow a space; the short "a"/"p" only counts right after a digit
# ("5p" yes, "plan 5 a day" no).
_AMPM = r"(a\.?m\.?|p\.?m\.?|(?<=\d)a|(?<=\d)p)"


def _hour24(h: int, ampm) -> int:
    if ampm:
        ampm = ampm[0].lower()
        if ampm == "p" and h < 12:
            return h + 12
        if ampm == "a" and h == 12:
            return 0
    return h


def _fmt(h: int, m: int) -> str:
    return f"{h:02d}:{m:02d}"


def _cut(text: str, m: re.Match) -> str:
    return text[:m.start()] + " " + text[m.end():]


def _safe_date(y, mo, d):
    try:
        return date(y, mo, d)
    except ValueError:
        return None


def _parse_time(text: str):
    """Returns (text_without_time, start 'HH:MM' | None, end 'HH:MM' | None)."""
    # Ranges: 2-3pm, 10:30am-12pm, 9 to 5pm, 14:00-15:30
    rng = re.search(
        rf"(?<![\w/])(?:at\s+|@\s*|from\s+)?(\d{{1,2}})(?::(\d{{2}}))?\s*{_AMPM}?"
        rf"\s*(?:-|–|to|until|till)\s*(\d{{1,2}})(?::(\d{{2}}))?\s*{_AMPM}?(?![\w/])",
        text, re.I)
    if rng and (rng.group(3) or rng.group(6) or rng.group(2) or rng.group(5)):
        h1, m1, ap1 = int(rng.group(1)), int(rng.group(2) or 0), rng.group(3)
        h2, m2, ap2 = int(rng.group(4)), int(rng.group(5) or 0), rng.group(6)
        if h1 <= 23 and h2 <= 23 and m1 < 60 and m2 < 60:
            if ap2 and not ap1:
                # "11-1pm" -> 11am-1pm ; "2-3pm" -> 2pm-3pm
                cand = _hour24(h1, ap2)
                ap1 = ap2 if cand <= _hour24(h2, ap2) else ("a" if ap2[0].lower() == "p" else "p")
            start = _hour24(h1, ap1)
            end = _hour24(h2, ap2 or ap1)
            return _cut(text, rng), _fmt(start, m1), _fmt(end, m2)

    single = re.search(rf"(?<![\w/])(?:at\s+|@\s*)?(\d{{1,2}})(?::(\d{{2}}))?\s*{_AMPM}(?![\w])",
                       text, re.I)
    if single and int(single.group(1)) <= 12:
        h = _hour24(int(single.group(1)), single.group(3))
        return _cut(text, single), _fmt(h, int(single.group(2) or 0)), None

    clock = re.search(r"(?<![\w/:])(?:at\s+|@\s*)?([01]?\d|2[0-3]):([0-5]\d)(?![\w:])", text, re.I)
    if clock:
        h = int(clock.group(1))
        if clock.group(0).lower().startswith(("at", "@")) and 1 <= h <= 7:
            h += 12   # "at 3:30" almost always means afternoon
        return _cut(text, clock), _fmt(h, int(clock.group(2))), None

    bare_at = re.search(r"(?<![\w])(?:at|@)\s*(\d{1,2})(?![\w:/])", text, re.I)
    if bare_at and 1 <= int(bare_at.group(1)) <= 12:
        h = int(bare_at.group(1))
        if h <= 7:
            h += 12
        return _cut(text, bare_at), _fmt(h, 0), None

    for word, hhmm in (("noon", "12:00"), ("midnight", "00:00")):
        m = re.search(rf"(?:at\s+)?\b{word}\b", text, re.I)
        if m:
            return _cut(text, m), hhmm, None
    return text, None, None


def _parse_date(text: str, today: date):
    """Returns (text_without_date, date | None)."""
    patterns = []

    def rule(regex, fn):
        patterns.append((re.compile(_PREFIX + regex, re.I), fn))

    def iso(m):
        return _safe_date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
    rule(r"\b(\d{4})-(\d{1,2})-(\d{1,2})\b", iso)

    def us(m):
        mo, d = int(m.group(1)), int(m.group(2))
        if m.group(3):
            y = int(m.group(3))
            y = y + 2000 if y < 100 else y
            return _safe_date(y, mo, d)
        dt = _safe_date(today.year, mo, d)
        if dt and dt < today:
            dt = _safe_date(today.year + 1, mo, d)
        return dt
    # "12/20" is a date, but "1/2 gallon" or "2/3 of the book" is a fraction: a bare m/d
    # followed by a word only counts when a cue word ("on", "due", "by"...) comes first.
    patterns.append((re.compile(
        r"(?:due|by|on|starting|start|from|beginning)\s+(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?(?![\w/])", re.I), us))
    rule(r"(?<![\w/])(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?(?![\w/])"
         r"(?!\s+(?!(?:at|from|to|and)\b)[A-Za-z])", us)

    def month_day(m):
        mo = MONTHS[m.group(1).lower()]
        d = int(m.group(2))
        if m.group(3):
            return _safe_date(int(m.group(3)), mo, d)
        dt = _safe_date(today.year, mo, d)
        if dt and dt < today:
            dt = _safe_date(today.year + 1, mo, d)
        return dt
    rule(rf"\b({_MONTH_RE})\.?\s+(\d{{1,2}})(?:st|nd|rd|th)?\b(?:,?\s+(\d{{4}}))?", month_day)

    def day_month(m):
        mo = MONTHS[m.group(2).lower()]
        d = int(m.group(1))
        if m.group(3):
            return _safe_date(int(m.group(3)), mo, d)
        dt = _safe_date(today.year, mo, d)
        if dt and dt < today:
            dt = _safe_date(today.year + 1, mo, d)
        return dt
    rule(rf"\b(\d{{1,2}})(?:st|nd|rd|th)?\s+(?:of\s+)?({_MONTH_RE})\b(?:,?\s+(\d{{4}}))?", day_month)

    rule(r"\b(?:the\s+)?day\s+after\s+tomorrow\b", lambda m: today + timedelta(days=2))
    rule(r"\b(?:today|tonight|tod)\b", lambda m: today)
    rule(r"\b(?:tomorrow|tmrw|tmr|tomorow)\b", lambda m: today + timedelta(days=1))

    def in_n(m):
        n = m.group(1).lower()
        n = 1 if n in ("a", "an", "one") else int(n) if n.isdigit() else None
        if n is None:
            return None
        unit = m.group(2).lower().rstrip("s")
        return today + {"day": relativedelta(days=n), "week": relativedelta(weeks=n),
                        "month": relativedelta(months=n), "year": relativedelta(years=n)}[unit]
    rule(r"\bin\s+(\d+|a|an|one)\s+(days?|weeks?|months?|years?)\b", in_n)

    rule(r"\bnext\s+week\b", lambda m: today + timedelta(days=7))
    rule(r"\bnext\s+month\b", lambda m: today + relativedelta(months=1))

    def weekday(m):
        target = recurrence.weekday_index(m.group(2))
        delta = (target - today.weekday()) % 7
        if m.group(1) and m.group(1).lower().startswith("next") and delta == 0:
            delta = 7
        return today + timedelta(days=delta)
    full_days = "monday|tuesday|wednesday|thursday|friday|saturday|sunday"
    rule(rf"\b(next\s+|this\s+)?({full_days})\b(?![\'’]s)", weekday)   # not "Monday's meeting"
    # Short forms ("sat", "sun", "wed") only count with a lead-in word,
    # so "buy sun cream" stays a title.
    patterns.append((re.compile(
        rf"\b(next\s+|this\s+|on\s+|due\s+|by\s+)({_WD_RE})\b(?![\'’]s)", re.I), weekday))

    def on_the(m):
        d = int(m.group(1))
        dt = _safe_date(today.year, today.month, d)
        if dt is None or dt < today:
            nxt = today + relativedelta(months=1)
            dt = _safe_date(nxt.year, nxt.month, d)
        return dt
    rule(r"\bon\s+the\s+(\d{1,2})(?:st|nd|rd|th)\b", on_the)

    for regex, fn in patterns:
        m = regex.search(text)
        if m:
            dt = fn(m)
            if dt:
                return _cut(text, m), dt
    return text, None


# --------------------------------------------------------------------------
# #tags
# --------------------------------------------------------------------------
# A tag starts with a letter and may contain letters, digits, _ - and / (for
# nested tags like #home/garden, as in Obsidian). "#1" or "issue #42" are not tags.
TAG_RE = re.compile(r"(?<![\w/#&])#([A-Za-z][\w\-/]*)")


def extract_tags(text: str):
    """'Call Bob #work #Calls' -> ('Call Bob', ['work', 'calls'])"""
    tags = []
    for m in TAG_RE.finditer(text or ""):
        tag = m.group(1).lower().strip("/-")
        if tag and tag not in tags:
            tags.append(tag)
    cleaned = re.sub(r"\s+", " ", TAG_RE.sub(" ", text or "")).strip()
    return cleaned, tags


def tags_to_db(tags) -> str:
    """Stored with surrounding spaces (' work home/garden ') so LIKE '% work %' matches whole tags."""
    tags = [t for t in dict.fromkeys(tags or []) if t]
    return f" {' '.join(tags)} " if tags else ""


def tags_from_db(value) -> list:
    return (value or "").split()


def _clean_title(text: str) -> str:
    text = re.sub(r"\s+", " ", text).strip()
    # drop dangling connector words left behind after cutting dates/times
    for _ in range(3):
        text = re.sub(r"(?i)\s+(?:on|at|by|due|from|starting|and|,|-|–)$", "", text).strip()
        text = re.sub(r"(?i)^(?:on|at|by|due)\s+", "", text).strip()
    return text.strip(" ,;-–")


def parse(text: str, today: date) -> dict:
    original = text
    # "event: ..." asks for a calendar event; a time range ("2-3pm") suggests one.
    kind_hint = "task"
    m = re.match(r"\s*(event|ev|cal)\s*:\s*", text, re.I)
    if m:
        kind_hint = "event"
        text = text[m.end():]
    m = re.match(r"\s*(task|todo)\s*:\s*", text, re.I)
    if m:
        text = text[m.end():]

    # Tags first, so "#friday" stays a tag instead of becoming a date.
    text, tags = extract_tags(text)

    priority = 0
    pm = re.search(r"(?:^|\s)(!{1,3})(?=\s|$)", text)
    if pm:
        priority = len(pm.group(1))
        text = _cut(text, pm)

    rrule, recur_from = None, None
    rec = recurrence.parse_recurrence(text)
    if rec:
        rrule, recur_from, (s, e) = rec
        text = text[:s] + " " + text[e:]

    text, start_time, end_time = _parse_time(text)
    if end_time:
        kind_hint = "event"
    text, when = _parse_date(text, today)

    if rrule:
        when = recurrence.first_on_or_after(rrule, when or today)

    title = _clean_title(text) or _clean_title(extract_tags(original)[0])
    return {
        "title": title,
        "date": when.isoformat() if when else None,
        "time": start_time,
        "end_time": end_time,
        "rrule": rrule,
        "recur_from": recur_from or "due",
        "repeat_text": recurrence.describe(rrule) if rrule else "",
        "priority": priority,
        "tags": tags,
        "kind_hint": kind_hint,
    }
