#!/usr/bin/env python3
"""Summarize notes locally with Python 3. No packages, service, or API key required."""

from __future__ import annotations

import argparse
from collections import Counter
from dataclasses import dataclass, replace
from math import sqrt
from pathlib import Path
import re
import sys

MAX_LENGTH = 50_000
BULLET = re.compile(r"^(?:(?:[-*+•‣▪◦] +|\d{1,3}[.)] +|\[[ xX]\] +|[✓✔☐☑] +))+")
HEADING = re.compile(
    r"^(?:meeting notes|call notes|notes|overview|summary|discussion|updates?|status|"
    r"next steps|action items?|decisions?|follow[- ]ups?|background|key points|agenda)$",
    re.IGNORECASE,
)
ACTION_VERBS = (
    r"send|email|call|follow up|confirm|collect|check|review|reconcile|update|schedule|"
    r"file|submit|pay|request|prepare|share|verify|resolve|contact|ask|document|track|draft|"
    r"complete|finalize|add|provide|bring|transfer|defer|cancel|resend|attach|prioritize|monitor|compare"
)
ACTION = re.compile(r"^(?:please\s+)?(?:do not|don't|avoid|watch|wait|hold|" + ACTION_VERBS + r")\b", re.I)
ASSIGNED = re.compile(r"^(.{1,55}?)\s+(?:->|→|to)\s+((?:" + ACTION_VERBS + r")\b.*)$", re.I)
PREDICATE = re.compile(
    r"\s(?:am|is|are|was|were|becomes?|will|would|won['’]t|can|can['’]t|cannot|could|should|must|"
    r"may|might|need(?:s|ed)?|has|have|had|did|does|do|[a-z]+n['’]t|agreed|approved|asked|called|"
    r"chose|closed|confirmed|declined|decreased|decided|discussed|estimated|expect(?:s|ed)?|fell|"
    r"filed|found|grew|increased|left|lost|met|missed|moved|noted|paid|plans?|posted|received|"
    r"reported|requested|reviewed|rose|said|saved|scheduled|sent|stayed|show(?:s|ed)?|signed|started|"
    r"submitted|told|wants?|went|works?|wrote)\b",
    re.I,
)
IMPORTANT = re.compile(
    r"\b(?:approved|declined|rejected|decided|agreed|blocked|overdue|missing|not received|"
    r"(?:did|was|were|has|have|had|does|do|is|are|can|will|could|should|must) not|[a-z]+n['’]t|"
    r"cannot|past due|outstanding|discrepancy|risk|deadline|due)\b",
    re.I,
)
PRIORITY = re.compile(
    r"\b(?:due|deadline|by\s+(?:the\s+)?(?:mon(?:day)?|tue(?:sday)?|wed(?:nesday)?|"
    r"thu(?:rsday)?|fri(?:day)?|sat(?:urday)?|sun(?:day)?|tomorrow|today|\d)|"
    r"next\s+(?:week|month)|before|no later than)\b",
    re.I,
)
AMOUNT = re.compile(r"[$€£]\s*\d|\d\s*%|\b\d{1,2}[/-]\d{1,2}\b|\b(?:Q[1-4]|20\d{2})\b", re.I)
FIELD = re.compile(r"^([a-z][\w /&'’-]{0,36})\s*:\s*(.+)$", re.I | re.ASCII)
NUMERIC_FIELD = re.compile(
    r"^(?:budget|revenue|profit|loss|growth|expenses?|tax|balance|cash(?: on hand)?|sales|"
    r"costs?|income|rent|rate|total|headcount|variance|payroll|deposit|distribution|forecast|estimate|cap|target)$",
    re.I,
)
NAMED_ACTION = re.compile(r"^(?:action(?: items?)?|next steps?|to[- ]do|follow[- ]up)$", re.I)
SHORT_STATUS = re.compile(
    r"^(.+?)\s+((?:not )?(?:received|paid|approved|complete|completed|signed|submitted|filed|ready|"
    r"pending|outstanding|missing|overdue|paused|deferred|unchanged|due\b.*?)|on hold)\.?$",
    re.I,
)
TREND = re.compile(r"^(.{1,60}?) (up|down) ((?:by )?[-+]?[$€£]?\d.*)$", re.I)
OPENERS = [
    (re.compile(r"^reviewed (.+)$", re.I), "The notes record a review of "),
    (re.compile(r"^discussed (.+)$", re.I), "The notes record a discussion about "),
    (re.compile(r"^received (.+)$", re.I), "The notes record receipt of "),
    (re.compile(r"^need to (.+)$", re.I), "The notes identify a need to "),
    (re.compile(r"^need (.+)$", re.I), "The notes identify a need for "),
    (re.compile(r"^no changes? to (.+)$", re.I), "There are no changes to "),
    (re.compile(r"^waiting (?:on|for) (.+)$", re.I), "The notes record a wait for "),
]
ABBREVIATION = re.compile(
    r"\b(?:Mr|Mrs|Ms|Dr|Prof|St|vs|e\.g|i\.e|U\.S|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)\."
    r"(?=\s+[^\W_])",
    re.I,
)
TIME = re.compile(r"\b[ap]\.m\.(?=\s+[a-z0-9])")
INITIALS = re.compile(r"\b(?:[A-Z]\.){2,}(?=\s+[a-z])")
BOUNDARY = re.compile(r"(?:(?<=[.!?])|(?<=[.!?][\"”'’)]))\s+(?=[\"“'‘(]?[^\W_])")


def split_notes(notes: str, prose: bool = False) -> list[str]:
    parts = []
    for line in re.split(r"\r\n?|\n|\s+[•‣▪◦]\s+", notes):
        clean = BULLET.sub("", line.strip()).strip()
        if HEADING.fullmatch(clean.removesuffix(":")) or not any(char.isalnum() for char in clean):
            continue
        protected = ABBREVIATION.sub(lambda match: match[0].replace(".", "\uE000"), clean)
        protected = TIME.sub(lambda match: match[0].replace(".", "\uE000"), protected)
        protected = INITIALS.sub(lambda match: match[0].replace(".", "\uE000"), protected)
        pieces = BOUNDARY.split(protected)
        if not prose:
            pieces = [segment for piece in pieces for segment in piece.split(";")]
        for part in pieces:
            clean_part = BULLET.sub("", part.replace("\uE000", ".").strip()).strip()
            if any(char.isalnum() for char in clean_part):
                parts.append(clean_part)
    return parts


def sentence(text: str) -> str:
    value = text.rstrip(";:").strip()
    if not value:
        return ""
    prefix_length = len(value) - len(value.lstrip("“\"‘'("))
    value = value[:prefix_length] + value[prefix_length:prefix_length + 1].upper() + value[prefix_length + 1:]
    return value if re.search(r"[.!?][\"”'’)]*$", value) else value + "."


def as_subject(text: str) -> str:
    return re.sub(
        r"^(?:The|A|An|Tax|Budget|Bank|Operating|Quarterly|Client|Invoice|Invoices|Statements|"
        r"Cash|Payroll|Revenue|Expenses|Reconciliation|Payment|Payments|Deposit|Contract)\b",
        lambda match: match[0].lower(),
        text,
    )


def to_sentence(note: str) -> str:
    clean = " ".join(note.split())
    if re.search(r"\?[\"”'’)]*$", clean):
        return sentence(clean)

    labeled = FIELD.fullmatch(clean)
    if labeled:
        label, value = labeled.groups()
        if NAMED_ACTION.fullmatch(label) and ACTION.match(value):
            return sentence(value)
        if NUMERIC_FIELD.fullmatch(label) and re.match(r"^[-−+]?\s*[$€£]?\s*\d", value):
            return sentence(label + " is listed as " + value)
        combined = label + " " + value
        if SHORT_STATUS.fullmatch(combined) and not PREDICATE.search(value):
            return to_sentence(combined)
        if HEADING.fullmatch(label) or NAMED_ACTION.fullmatch(label):
            return to_sentence(value)
        return sentence("The notes list “" + value.removesuffix(".") + "” under “" + label + "”")

    if ACTION.match(clean):
        return sentence(clean)
    for pattern, prefix in OPENERS:
        match = pattern.fullmatch(clean)
        if match:
            return sentence(prefix + match[1])

    assignment = ASSIGNED.fullmatch(clean)
    if assignment and not PREDICATE.search(assignment[1]):
        return sentence("The next step for " + as_subject(assignment[1]) + " is to " + assignment[2])

    trend = TREND.fullmatch(clean)
    if trend and not PREDICATE.search(trend[1]):
        return sentence(trend[1] + (" rose " if trend[2].lower() == "up" else " fell ") + trend[3])
    status = SHORT_STATUS.fullmatch(clean)
    if status and not PREDICATE.search(status[1]):
        detail = status[2].removesuffix(".")
        due = re.match(r"^due\s+(.+)$", detail, re.I)
        if due:
            return sentence("The deadline for " + as_subject(status[1]) + " is " + re.sub(r"^(?:by|on) ", "", due[1], flags=re.I))
        return sentence("The notes mark " + as_subject(status[1]) + " as " + detail)

    if PREDICATE.search(clean):
        return sentence(clean)
    return sentence("The notes mention “" + clean.removesuffix(".") + "”")


NOTE_TYPES = {
    "general": "General",
    "response": "Response pros/cons",
    "educational": "Educational",
    "long": "Long text",
}

_STRENGTHS = r"pros?|positives?|strengths?|advantages?|good(?: points?)?|what worked(?: well)?"
_WEAKNESSES = (
    r"cons?|negatives?|weaknesses?|drawbacks?|issues?|limitations?|problems?|"
    r"what (?:didn['’]t|did not) work|needs improvement"
)
FEEDBACK_MARKER = re.compile(rf"^(?:({_STRENGTHS})|({_WEAKNESSES}))\s*(?::|[–—-]\s|$)\s*(.*)$", re.I)
INLINE_MARKER = re.compile(rf"\s+(?=(?:\*\*)?(?:{_STRENGTHS}|{_WEAKNESSES}):)", re.I)
RESPONSE_LABEL = re.compile(
    r"^(?:things wrong with\s+)?(response [a-z0-9]+|both(?: responses?)?)\s*"
    r"(?::|\s+(?=(?:pros?|cons?|strengths?|weaknesses?)\b)|$)\s*(.*)$", re.I,
)
NEGATIVE_FEEDBACK = re.compile(
    r"\b(?:not (?:accurate|clear|concise|helpful|supported)|omits?|missing|miss(?:es|ed)|fails? to|leaves? out|does(?:n['’]t| not)|lacks?|unclear|"
    r"incorrect|wrong|unsupported|inaccurate|overstates?|understates?|weak|contradicts?|vague|"
    r"insufficient|incomplete|unrealistic|too (?:short|long|vague)|errors?|needs? improvement|"
    r"no (?:sources?|citations?|examples?|details?))\b", re.I,
)
POSITIVE_FEEDBACK = re.compile(
    r"\b(?:clear(?:ly)?|accurate(?:ly)?|strong|useful|helpful|effective(?:ly)?|correct(?:ly)?|"
    r"well[- ](?:written|structured|organized|supported|explained)|concise|thorough|"
    r"specific examples?|explains?|addresses?|covers?|cites?)\b", re.I,
)
EVALUATION_VERB = re.compile(
    r"^(?:address(?:es|ed)|acknowledg(?:es|ed)|answer(?:s|ed)|avoid(?:s|ed)|cit(?:es|ed)|"
    r"compar(?:es|ed)|contradict(?:s|ed)|cover(?:s|ed)|demonstrat(?:es|ed)|describ(?:es|ed)|"
    r"distinguish(?:es|ed)|does(?:n['’]t| not)|draws?|emphasiz(?:es|ed)|explains?|explained|"
    r"fails?|failed|focuses|gives|gave|helps?|identif(?:ies|ied)|ignor(?:es|ed)|includ(?:es|ed)|"
    r"lacks?|leaves? out|list(?:s|ed)|makes?|made|mention(?:s|ed)|miss(?:es|ed)|misstat(?:es|ed)|"
    r"needs?|notes?|omit(?:s|ted)|overlook(?:s|ed)|overstat(?:es|ed)|present(?:s|ed)|"
    r"provid(?:es|ed)|recogniz(?:es|ed)|recommend(?:s|ed)|relies|restat(?:es|ed)|shows?|showed|"
    r"support(?:s|ed)|treat(?:s|ed)|understat(?:es|ed)|us(?:es|ed))\b", re.I,
)
BARE_EVALUATION_VERBS = set("draw explain fail help lack make miss need note omit show support".split())
EDUCATIONAL_VERB = re.compile(
    r"\s(?:absorb|add|allow|align|balance|build|break|cause|carry|compare|condens|contain|control|convert|create|"
    r"decrease|defend|define|depend|divide|drive|eat|emit|expand|explain|fall|feed|flow|form|"
    r"function|generate|happen|help|increase|indicate|interact|lead|limit|link|maintain|mean|"
    r"move|multiply|occur|pass|power|prevent|produce|protect|reach|react|refer|reflect|reform|regulate|"
    r"release|remove|require|result|return|rise|run|separat|settle|signal|spread|start|store|supply|"
    r"take|transfer|transform|transmit|travel|use|vary|yield)[a-z]{0,3}\b", re.I,
)
LEARNING_LABEL = re.compile(r"^([^\W\d_][\w ()/'’-]{0,58}?)\s*:\s*(.+)$")
LEARNING_EQUATION = re.compile(r"^[^\W\d_][\w ()/'’-]{0,58}?\s*=\s*.+$")
LEARNING_SIGNAL = re.compile(
    r"\b(?:defined? as|refers? to|means?|process by which|consists? of|because|causes?|"
    r"results? in|depends? on|converts?|requires?|produces?|difference between|proportional to)\b", re.I,
)
EXAMPLE = re.compile(r"^(?:for example|for instance|e\.g\.|examples?\s*:|practice(?: question)?\s*:)", re.I)
LOW_VALUE = re.compile(
    r"^(?:see also|read more|table of contents|references|bibliography|credits|all rights reserved|subscribe)\b", re.I,
)
STOP_WORDS = set((
    "about above across after again against also among and another are around back before below between both but can could "
    "did does doing done down during each either enough even every few first for from further get give given had has have "
    "having here how into its just last later least less like many may might more most much must near need neither next "
    "nor not now often once one only onto other our out over per really same say says said she should since some still such "
    "take than that the their them then there these they thing this those though through thus together too toward under until "
    "upon use used using very was well were what when where whether which while who will with within without would yet you your"
).split())
CONTEXT_START = re.compile(
    r"^(?:it|they|this|these|those|he|she|however|therefore|additionally|"
    r"for example|for instance|in other words)\b", re.I,
)
MAIN_FINDING = re.compile(
    r"\b(?:aims? to|purpose|findings?|found|conclud(?:es?|ed)|results? (?:show|suggest|indicate)|"
    r"overall|because|in response|voted to|decided to)\b", re.I,
)


def note_key(text: str) -> str:
    return " ".join(text.lower().rstrip(".!?").split())


def lower_start(text: str) -> str:
    return re.sub(
        r"^(?:A|An|The|It|This|These|Those|Some|No|Clear|Strong|Useful|Good|Specific|"
        r"Accurate|Incorrect|Unclear|Weak|Incomplete|Poor|Misleading|Limited)\b",
        lambda match: match[0].lower(),
        text,
    )


@dataclass(frozen=True)
class Feedback:
    text: str
    tone: int
    scope: str
    order: int = 0
    kind: str = ""
    bonus: int = 0
    combined: bool = False
    uncited: str = ""

    @property
    def score(self) -> int:
        return min(len(self.text.split()), 13) + self.bonus


def render_feedback(note: Feedback) -> str:
    text, tone, scope = note.text, note.tone, note.scope
    subject = "Each response" if scope == "Both responses" else scope or "The response"
    if re.match(r"^(?:is|was|has)\s", text, re.I):
        return sentence(subject + " " + text[0].lower() + text[1:])
    pronoun = re.match(r"^(?:it|this response|the response|the answer)\s+(.+)$", text, re.I)
    if pronoun:
        return sentence(subject + " " + pronoun[1])
    verb_match = EVALUATION_VERB.match(text)
    if verb_match:
        verb = verb_match[0].lower()
        if verb in BARE_EVALUATION_VERBS:
            verb += "es" if verb == "miss" else "s"
        return sentence(subject + " " + verb + text[len(verb_match[0]):])
    missing = re.match(r"^(?:is )?missing\s+(.+)$", text, re.I)
    if missing:
        return sentence(subject + " omits " + lower_start(missing[1]))
    no = re.match(r"^no\s+(.+)$", text, re.I)
    if no and tone < 0:
        return sentence(subject + " provides no " + no[1])
    if re.match(r"^response [a-z0-9]+\b", text, re.I) or PREDICATE.search(text) or EDUCATIONAL_VERB.search(text):
        return sentence(text)
    point = lower_start(text.removesuffix("."))
    if re.fullmatch(
        r"(?:clear|accurate|concise|thorough|helpful|useful|"
        r"well[- ](?:organized|structured|written|explained|supported)|unclear|inaccurate|vague|"
        r"too (?:short|long|technical|vague))", point, re.I,
    ):
        return sentence(subject + " is " + point.lower())
    if tone:
        owner = "both responses’" if scope == "Both responses" else scope + "’s" if scope else "the response’s"
        quality = " strengths" if tone > 0 else " weaknesses"
        return sentence(owner + quality + " include " + point)
    return sentence("The feedback highlights “" + point + "”")


def infer_tone(text: str) -> int:
    return -1 if NEGATIVE_FEEDBACK.search(text) else 1 if POSITIVE_FEEDBACK.search(text) else 0


def feedback_parts(note: str, tone: int) -> list[tuple[str, int]]:
    contrast = re.fullmatch(r"(.+?)\s*,?\s+but\s+(.+)", note, re.I)
    if contrast and not re.search(r"\bnot only\b", contrast[1], re.I):
        first, second = infer_tone(contrast[1]), infer_tone(contrast[2])
        if first * second < 0:
            return [(contrast[1], first), (contrast[2], second)]
    return [(note, tone or infer_tone(note))]


FEEDBACK_TITLE = re.compile(
    r'^((?:["“][^"”]{1,76}["”]|[^\W\d_][\w ()/.,&+\'’–—-]{0,69}))\s*:\s*(?!/)\s*(\S.*)$',
)
NO_CITATION = re.compile(
    r"^(?:no (?:sources?|citations?|references?|evidence)(?: (?:is|are|was|were))?"
    r"(?: (?:given|provided|cited|listed|included|offered))?|(?:(?:is|was) )?"
    r"(?:unsubstantiated|uncited|unsourced)|(?:lacks?|missing) (?:a )?(?:source|citation|reference|evidence))$",
    re.I,
)
LIMITED_SUPPORT = re.compile(r"^(.+?)\s+(?:rests on|relies on|is based on|draws on)\s+(.+?),?\s+with no\s+(.+)$", re.I)
TARIFF_TREATMENT = re.compile(
    r"^(?:it|the [\w -]{1,40}) (?:includes?|lists?|covers?|has) (.+?),\s+which (.{1,55}?) "
    r"(bills?|charges?|classifies?|treats?) as (.+)$",
    re.I,
)
EXPLANATION = re.compile(
    r"^(?:that(?:’s|'s| is)|this is) why (.+)$|^(?:(?:this|that|which) explains why|therefore,?)\s+(.+)$",
    re.I,
)
CONSEQUENCE = re.compile(r"^(?:this|that) ((?:means|shows|suggests|implies|explains|causes|leaves) .+)$", re.I)
UNCHANGED_VERSION = re.compile(
    r"^((?:an?|the) .+?\b(?:version|edition|revision) of .+?) exists,?\s+with (?:the )?same "
    r"(content|wording|language) on (both|(?:these|those)) points$",
    re.I,
)
FEEDBACK_CLAUSE = re.compile(
    r"\s(?:cites?|covers?|describes?|explains?|ignores?|includes?|lacks?|lists?|miss(?:es)?|omits?|overlooks?|provides?|shows?|states?)\s+", re.I,
)
GENERIC_TOPIC = re.compile(
    r"^(?:accuracy|clarity|citations?|conclusion|coverage|detail|evidence|examples?|"
    r"format(?:ting)?|organization|sources?|structure|tone|wording)$",
    re.I,
)
FOLLOW_ON = re.compile(
    r"\n[ \t]*(?=(?:(?:that(?:’s|'s| is)|this is) why|(?:this|that|which) explains why|"
    r"(?:this|that) (?:means|shows|suggests|implies|causes|leaves)|therefore)\b)",
    re.I,
)


def fragment(text: str) -> str:
    return " ".join(text.split()).rstrip(".!;:")


def topic_name(title: str) -> str:
    bare = title.strip('“”"').strip()
    if re.match(r"^\S+['’]s\s", bare):
        return bare
    return bare[0].lower() + bare[1:] if bare[:1].isupper() and bare[1:2].islower() else bare


def topic_subject(title: str) -> str:
    name = topic_name(title)
    statement = PREDICATE.search(name) or re.search(
        r"\s(?:starts?|ends?|finishes?|costs?|exceeds?)\s+(?:in|on|by|after|before|more|less|[$€£\d])", name, re.I,
    )
    if title.startswith(('"', "“")) and statement:
        return "the claim that " + name
    if re.match(r"^(?:how|when|where|whether|why|what|which|who)\b", name, re.I):
        return "the point about " + name
    if re.match(r"^(?:a|an|the)\s|^\S+['’]s\s", name, re.I):
        return name
    return "the " + name


def name_claim(claim: str, title: str) -> str:
    name = topic_name(title)
    match = re.fullmatch(r"((?:(?:the|a|an) )?)(.+?) (risk|estimate|forecast|projection|timeline|schedule)", claim, re.I)
    if not match or not re.fullmatch(r"[^\W\d_]+(?:-[^\W\d_]+)*", name) or GENERIC_TOPIC.fullmatch(name) or name.lower() in claim.lower():
        return claim
    return f"{match[1]}{match[2]} {name} {match[3]}"


def comparison_in_costs(text: str, verb: str) -> str:
    comparison = re.fullmatch(r"([^\W\d_]+(?:-[^\W\d_]+)*) (always )?exceeds ([^\W\d_]+(?:-[^\W\d_]+)*)", text, re.I)
    if not comparison or not re.fullmatch(r"bills?|charges?", verb, re.I):
        return text
    first, always, second = comparison.groups()
    return f"{first} costs {'consistently ' if always else ''}exceed {second} costs"


def titled_feedback(title: str, notes: list[str], tone: int, scope: str) -> list[Feedback]:
    subject = topic_subject(title)
    head, *details = (fragment(note) for note in notes)
    support = LIMITED_SUPPORT.fullmatch(head)
    treatment = TARIFF_TREATMENT.fullmatch(head)
    version = UNCHANGED_VERSION.fullmatch(head)
    reason_index = next((index for index, text in enumerate(details) if EXPLANATION.fullmatch(text) or CONSEQUENCE.fullmatch(text)), -1)
    reason = details[reason_index] if reason_index >= 0 else ""
    why = EXPLANATION.fullmatch(reason)
    effect = CONSEQUENCE.fullmatch(reason)
    text, kind, used_reason = head, "detail", False
    no_source = bool(NO_CITATION.fullmatch(head))
    generic = bool(GENERIC_TOPIC.fullmatch(topic_name(title)))
    unsubstantiated = bool(re.search(r"\b(?:evidence|unsubstantiated)\b", head, re.I))
    if no_source:
        if unsubstantiated:
            text = "the response leaves its claims unsupported" if generic else subject + " lacks supporting evidence"
        else:
            text = "the response gives no source" if generic else subject + " lacks a cited source"
        kind = "evidence"
    elif support:
        claim, source, gap = support.groups()
        narrow_date = re.fullmatch(r"(schedule|timeline|date|plan) for ((?:19|20)\d{2})", gap, re.I)
        gap = f"{narrow_date[2]} {narrow_date[1]}" if narrow_date else gap
        text = f"{name_claim(claim, title)} relies on {source} with no {gap}"
        kind = "evidence"
    elif treatment:
        items, authority, verb, category = treatment.groups()
        category = re.sub(r'["“]([^"”]+)["”](?= (?:charges|fees|rates)\b)', r"\1", category, flags=re.I)
        text = f"{authority} {verb} {items} as {category}"
        if why:
            text = comparison_in_costs(lower_start(why[1] or why[2]), verb) + " because " + lower_start(text)
            used_reason = True
        kind = "explanation"
    elif version:
        points = "the same two points" if version[3].lower() == "both" else "the same points"
        wording = f" covers {points}" if version[2].lower() == "content" else f" keeps the same {version[2]} on {points}"
        text = version[1] + wording
        kind = "revision"
    else:
        omission = re.match(r"^(?:omits?|(?:is )?missing|leaves? out|fails? to (?:mention|include|address))\s+(.+)$", head, re.I)
        if omission:
            text = "the response leaves out " + lower_start(omission[1])
        elif re.match(r"^it\s", head, re.I):
            explicit_subject = not generic and re.search(
                r"\b(?:column|section|table|chart|report|policy|plan|method|schedule|example|summary|analysis|breakdown)$", topic_name(title), re.I,
            )
            text = (subject if explicit_subject else "the response") + head[2:]
        elif EVALUATION_VERB.match(head) or (not FEEDBACK_CLAUSE.search(head) and (tone or infer_tone(head))):
            text = fragment(render_feedback(Feedback(head, tone or infer_tone(head), "")))
        elif not (FEEDBACK_CLAUSE.search(head) or PREDICATE.search(head) or EDUCATIONAL_VERB.search(head)):
            text = "the feedback on " + subject + " points to " + lower_start(head)

    if reason and not used_reason and "?" not in head:
        text += ", which explains why " + lower_start(why[1] or why[2]) if why else ", which " + effect[1]
        used_reason = True
    labeled_tone = tone or (-1 if kind == "evidence" else infer_tone(head))
    uncited = subject if no_source and not unsubstantiated and not generic else ""
    points = [Feedback(text, labeled_tone, scope, kind=kind, bonus=0 if kind == "detail" else 4, uncited=uncited)]
    for index, detail in enumerate(details):
        if (used_reason and index == reason_index) or re.match(r"^(?:it|this|that|these|those|they|which)\b", detail, re.I):
            continue
        points.append(Feedback(detail, tone or infer_tone(detail), scope, kind="detail", bonus=-2))
    return points


def group_feedback(items: list[Feedback]) -> list[Feedback]:
    grouped = []
    for item in items:
        if item.kind == "evidence":
            peer_index = next((
                index for index, point in enumerate(grouped)
                if point.kind == "evidence" and point.scope == item.scope and point.tone == item.tone
                and not point.combined and len(point.text.split()) + len(item.text.split()) <= 48
            ), -1)
            if peer_index >= 0:
                peer = grouped[peer_index]
                if peer.uncited and item.uncited:
                    text = f"the response cites no source for {lower_start(peer.uncited)} or for {lower_start(item.uncited)}"
                else:
                    text = peer.text + ", and " + lower_start(item.text)
                rank = max(peer.score, item.score) + 2
                grouped[peer_index] = replace(peer, text=text, combined=True, bonus=rank - min(len(text.split()), 13))
                continue
        grouped.append(item)
    return grouped


def render_titled(point: Feedback) -> str:
    text = point.text
    if point.scope:
        owner = "each response" if point.scope == "Both responses" else point.scope
        if re.match(r"^the response\b", text, re.I):
            text = re.sub(r"^the response\b", owner, text, count=1, flags=re.I)
        else:
            group = "both responses" if point.scope == "Both responses" else point.scope
            text = f"In {group}, {lower_start(text)}"
    return sentence(text)


def summarize_feedback(notes: str) -> str:
    signed = bool(re.search(r"^\s*\+\s+", notes, re.M))
    seen = set()
    candidates = []
    scope, tone = "", 0
    blocks = FOLLOW_ON.sub(" ", re.sub(r"\r\n?", "\n", notes))
    for line in re.split(r"\n|(?<=[.!?])\s+(?=(?:\*\*)?(?:Pros?|Cons?):)", blocks, flags=re.I):
        raw = line.strip()
        sign = re.match(r"^([+-])\s+", raw)
        clean = re.sub(r"^\s*#+\s+", "", BULLET.sub("", raw)).replace("**", "").strip()
        if not clean:
            continue
        named = RESPONSE_LABEL.fullmatch(clean)
        if named:
            scope = "Both responses" if named[1].lower().startswith("both") else "Response " + named[1][9:].upper()
            tone = -1 if clean.lower().startswith("things wrong") else 0
            clean = named[2]
        if re.fullmatch(r"(?:pros\s*[/&]\s*cons|pros and cons|response feedback|feedback)\s*:?", clean, re.I):
            tone = 0
            continue
        for segment in INLINE_MARKER.split(clean):
            marker = FEEDBACK_MARKER.fullmatch(segment)
            if marker:
                tone, segment = (1 if marker[1] else -1), marker[3]
            inferred = 1 if sign and sign[1] == "+" else -1 if sign and signed else 0
            labeled = FEEDBACK_TITLE.fullmatch(segment.strip())
            parts = split_notes(labeled[2] if labeled else segment)
            if labeled and parts:
                points = titled_feedback(labeled[1], parts, tone or inferred, scope)
            else:
                points = [Feedback(text, label, scope) for note in parts for text, label in feedback_parts(note, tone or inferred)]
            for point in points:
                key = point.scope, point.tone, note_key(point.text)
                if key in seen:
                    continue
                seen.add(key)
                candidates.append(replace(point, order=len(candidates)))

    ranked = sorted(group_feedback(candidates), key=lambda note: -note.score)
    strongest = next((note for note in ranked if note.tone > 0), None)
    weakest = next((note for note in ranked if note.tone < 0), None)
    selected = [item for item in (strongest, weakest) if item]
    scopes = {item.scope for item in selected}
    other = next((item for item in ranked if item.scope and item.scope not in scopes), None)
    for item in (other, *ranked):
        if len(selected) == 3:
            break
        if item and item not in selected:
            selected.append(item)
    titled_only = all(note.kind for note in selected)
    ordered = sorted(selected, key=lambda note: (0 if titled_only else -note.tone, note.order))
    rendered = [render_titled(note) if note.kind else render_feedback(note) for note in ordered]
    return " ".join(
        re.sub(r"^The response ", "It ", text) if index and re.match(r"^The response\b", rendered[index - 1]) else text
        for index, text in enumerate(rendered)
    )


def render_learning(note: str) -> str:
    note = re.sub(r"^(?:(?:key (?:idea|point|concept)|definition|takeaway|summary)\s*:\s*(?=\S))+", "", note, flags=re.I)
    labeled = LEARNING_LABEL.fullmatch(note)
    if labeled:
        term, value = labeled.groups()
        if re.fullmatch(r"formula|equation", term, re.I):
            return sentence("The notes give the equation " + value)
        if re.fullmatch(r"examples?", term, re.I):
            return sentence("The notes give “" + value.removesuffix(".") + "” as an example")
        if (re.match(r"^(?:a|an|the) (?:process|method|theory|measure|force|type|study|amount|rate|ratio|change|ability)\b", value, re.I)
                and not re.search(r"\band\b", term, re.I)
                and (not term.lower().endswith("s") or term.lower().endswith(("sis", "is", "us", "ss")))):
            return sentence(term + " is " + value)
        if (PREDICATE.search(value) or EDUCATIONAL_VERB.search(value)) and not re.match(
            r"^(?:(?:a|an|the)\s+)?(?:process|system|method|theory|measure|force|group|type|"
            r"set|study|amount|rate|ratio|change|ability)\b", value, re.I,
        ):
            return sentence("For " + lower_start(term) + ", the notes explain that " + lower_start(value))
        return sentence("The notes describe " + lower_start(term) + " as " + lower_start(value))
    if LEARNING_EQUATION.fullmatch(note):
        return sentence("The notes give " + note)
    relation = re.fullmatch(r"(.+?)\s*(?:→|->)\s*(.+)", note)
    if relation:
        return sentence("The notes link " + lower_start(relation[1]) + " to " + lower_start(relation[2]))
    if PREDICATE.search(note) or EDUCATIONAL_VERB.search(note):
        return sentence(note)
    return to_sentence(note)


def distinct_notes(notes: str, prose: bool = False) -> list[str]:
    seen = set()
    unique = []
    for item in split_notes(notes, prose=prose):
        text = " ".join(item.split())
        key = note_key(text)
        if key not in seen and not LOW_VALUE.match(text):
            seen.add(key)
            unique.append(text)
    return unique


def summarize_learning(notes: str) -> str:
    candidates = []
    for note in distinct_notes(notes):
        if re.fullmatch(r"(?:chapter|unit|lesson|lecture|week)\s+\d+\s*(?::\s*[^.!?]+)?", note, re.I):
            continue
        score = (
            4 * bool(LEARNING_SIGNAL.search(note))
            + 3 * bool(LEARNING_LABEL.fullmatch(note) and not EXAMPLE.match(note))
            + 2 * bool(LEARNING_EQUATION.fullmatch(note) or "→" in note or "->" in note)
            + 2 * bool(PREDICATE.search(note) or EDUCATIONAL_VERB.search(note))
            - 4 * bool(EXAMPLE.match(note))
        )
        candidates.append((score, len(candidates), note))
    selected = sorted(candidates, key=lambda item: (-item[0], item[1]))[:3]
    return " ".join(render_learning(note) for _, _, note in sorted(selected, key=lambda item: item[1]))


def content_terms(text: str) -> set[str]:
    words = re.findall(r"[^\W\d_][^\W_]{2,}", text.lower())
    return {
        re.sub(r"(?<!s)s$", "", re.sub(r"ies$", "y", word)) if len(word) > 4 else word
        for word in words if word not in STOP_WORDS
    }


def summarize_long_text(notes: str) -> str:
    wrapped = re.sub(r"\r\n?", "\n", notes)
    wrapped = re.sub(r"(?<=[^.!?\n])\n(?=[^\n•‣▪◦*+\-#\d])", " ", wrapped)
    texts = distinct_notes(wrapped, prose=True)
    terms = [content_terms(text) for text in texts]
    occurrences = Counter(word for words in terms for word in words)
    scores = []
    for order, (text, words) in enumerate(zip(texts, terms)):
        size = len(text.split())
        topicality = sum(min(3, sqrt(occurrences[word] - 1)) for word in words) / max(3, sqrt(len(words)) * 2)
        scores.append(
            topicality + .55 * bool(MAIN_FINDING.search(text)) + (.65 if order == 0 else .3 if order == 1 else 0)
            - .6 * bool(CONTEXT_START.match(text)) - .9 * (size < 7) - .45 * (size > 52)
        )

    def rank(index: int) -> float:
        similarity = max(
            (len(terms[index] & terms[other]) / max(1, len(terms[index] | terms[other])) for other in selected),
            default=0,
        )
        return scores[index] - 1.75 * similarity

    limit = 3 if len(notes.split()) >= 400 else 2
    remaining = list(range(len(texts)))
    selected = []
    while remaining and len(selected) < limit:
        best = max(remaining, key=rank)
        selected.append(best)
        remaining.remove(best)
    return " ".join(sentence(texts[index]) for index in sorted(selected))


def summarize_notes(notes: str, note_type: str = "general") -> str:
    """Return a short summary tailored to the selected note type."""
    notes = notes.strip()
    if not notes:
        return ""
    if len(notes) > MAX_LENGTH:
        raise ValueError("Use 50,000 characters or fewer.")
    if note_type == "response":
        return summarize_feedback(notes)
    if note_type == "educational":
        return summarize_learning(notes)
    if note_type == "long":
        return summarize_long_text(notes)

    seen = set()
    candidates = []
    for note in split_notes(notes):
        key = " ".join(note.lower().rstrip(".!?").split())
        if key in seen:
            continue
        seen.add(key)
        score = (
            3 * bool(IMPORTANT.search(note))
            + 3 * bool(ACTION.match(note) or ASSIGNED.match(note))
            + 2 * bool(PRIORITY.search(note))
            + 2 * bool(AMOUNT.search(note))
        )
        candidates.append((score, len(candidates), note))

    limit = 3 if len(candidates) > 2 else 2
    selected = sorted(candidates, key=lambda item: (-item[0], item[1]))[:limit]
    return " ".join(to_sentence(note) for _, _, note in sorted(selected, key=lambda item: item[1]))


def launch_window(note_type: str = "general") -> int:
    """Open the optional desktop interface using Python's Tkinter module."""
    try:
        import tkinter as tk
        from tkinter import ttk
        from tkinter.scrolledtext import ScrolledText
    except ImportError:
        print("Tkinter is needed for the desktop window. Run with a notes file or pipe in text for terminal use.", file=sys.stderr)
        return 1

    try:
        root = tk.Tk()
    except tk.TclError as exc:
        print(f"Could not open the desktop window ({exc}). Terminal mode is available.", file=sys.stderr)
        return 1

    root.title("Note Summarizer | Greer Financial")
    root.configure(bg="#f6f7f3")
    root.geometry("920x515")
    root.minsize(660, 390)
    root.columnconfigure((0, 1), weight=1, uniform="panes")
    root.rowconfigure(2, weight=1)

    green, ink, background = "#254a3a", "#202c26", "#f6f7f3"
    tk.Label(root, text="Greer Financial", bg=background, fg=green,
             font=("TkDefaultFont", 11, "bold")).grid(row=0, column=0, sticky="w", padx=17, pady=(15, 0))
    tk.Label(root, text="Note Summarizer", bg=background, fg=ink,
             font=("Georgia", 30)).grid(row=1, column=0, columnspan=2, sticky="w", padx=15, pady=(2, 14))

    panes = []
    fields = []
    for column, label in enumerate(("Your notes", "Summary")):
        pane = tk.Frame(root, bg="#ffffff", highlightbackground="#dce2db", highlightthickness=1)
        pane.grid(row=2, column=column, sticky="nsew", padx=(16, 7) if not column else (7, 16))
        pane.rowconfigure(1, weight=1)
        pane.columnconfigure(0, weight=1)
        tk.Label(pane, text=label, bg="#ffffff", fg=ink, font=("TkDefaultFont", 11, "bold")).grid(
            row=0, column=0, sticky="w", padx=13, pady=(12, 3)
        )
        field = ScrolledText(pane, wrap="word", relief="flat", padx=9, pady=7,
                             font=("TkDefaultFont", 11), fg=ink, undo=False, width=1, height=1)
        field.grid(row=1, column=0, sticky="nsew", padx=5, pady=(0, 5))
        panes.append(pane)
        fields.append(field)

    controls = tk.Frame(panes[1], bg="#ffffff")
    controls.grid(row=0, column=0, sticky="e", padx=10, pady=(8, 2))
    tk.Label(controls, text="Note type", bg="#ffffff", fg=green).pack(side="left", padx=(0, 6))
    chooser = ttk.Combobox(controls, values=list(NOTE_TYPES.values()), state="readonly", width=17)
    chooser.set(NOTE_TYPES[note_type])
    chooser.pack(side="left")

    notes, result = fields
    result.configure(state="disabled")
    status = tk.StringVar(value="Notes and summaries are cleared when you close this window.")

    def set_result(text: str) -> None:
        result.configure(state="normal")
        result.delete("1.0", "end")
        result.insert("1.0", text)
        result.configure(state="disabled")
        copy_button.configure(state="normal" if text else "disabled")

    def summarize() -> None:
        try:
            selected_type = next(key for key, label in NOTE_TYPES.items() if label == chooser.get())
            text = summarize_notes(notes.get("1.0", "end-1c"), selected_type)
        except ValueError as exc:
            set_result("")
            status.set(str(exc))
            return
        set_result(text)
        status.set("Summary ready to copy." if text else "Paste or type your notes first.")

    def clear() -> None:
        notes.delete("1.0", "end")
        set_result("")
        notes.focus_set()
        status.set("Notes and summary cleared.")

    def copy() -> None:
        root.clipboard_clear()
        root.clipboard_append(result.get("1.0", "end-1c"))
        status.set("Summary copied.")

    def edited(_event: tk.Event) -> None:
        if notes.edit_modified():
            notes.edit_modified(False)
            set_result("")
            status.set("")

    input_actions = tk.Frame(panes[0], bg="#ffffff")
    input_actions.grid(row=2, column=0, sticky="e", padx=10, pady=(4, 10))
    tk.Button(input_actions, text="Clear", command=clear, padx=12).pack(side="left", padx=(0, 7))
    tk.Button(input_actions, text="Summarize", command=summarize, bg=green, fg="#ffffff",
              activebackground="#1c3a2d", activeforeground="#ffffff", padx=12).pack(side="left")
    copy_button = tk.Button(panes[1], text="Copy", command=copy, state="disabled", padx=12)
    copy_button.grid(row=2, column=0, sticky="e", padx=10, pady=(4, 10))
    tk.Label(root, textvariable=status, bg=background, fg=ink).grid(
        row=3, column=0, columnspan=2, sticky="w", padx=17, pady=11
    )
    notes.bind("<<Modified>>", edited)
    chooser.bind("<<ComboboxSelected>>", lambda _event: summarize() if result.get("1.0", "end-1c") else None)
    notes.focus_set()
    root.mainloop()
    return 0


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("notes_file", nargs="?", type=Path, help="Read a UTF-8 text file. Omit to read standard input.")
    parser.add_argument("--type", choices=NOTE_TYPES, default="general", help="Choose the note type.")
    parser.add_argument("--gui", action="store_true", help="Open the desktop window.")
    args = parser.parse_args()
    if args.gui:
        if args.notes_file:
            parser.error("Use --gui or a notes file separately.")
        return launch_window(args.type)

    if args.notes_file is None and sys.stdin.isatty():
        print("Paste your notes, then press Ctrl-D (macOS/Linux) or Ctrl-Z and Enter (Windows).", file=sys.stderr)

    try:
        if args.notes_file:
            with args.notes_file.open(encoding="utf-8-sig") as file:
                notes = file.read(MAX_LENGTH + 1)
        else:
            notes = sys.stdin.read(MAX_LENGTH + 1)
        if len(notes) > MAX_LENGTH:
            raise ValueError("Use 50,000 characters or fewer.")
        summary = summarize_notes(notes, args.type)
    except (OSError, UnicodeError, ValueError) as exc:
        print(f"Couldn't summarize the notes. {exc}", file=sys.stderr)
        return 1

    if not summary:
        print("Add a note with words or numbers to summarize.", file=sys.stderr)
        return 1
    print(summary)
    return 0


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