#!/usr/bin/python3
import gi, re
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

def check_grammar(text):
    issues = []
    words = text.split()
    # repeated words
    for i in range(len(words)-1):
        if words[i].lower() == words[i+1].lower():
            issues.append(f'Line ~: Repeated word: "{words[i]}"')
    # sentences
    sentences = re.split(r'[.!?]+', text)
    for i, s in enumerate(sentences):
        s = s.strip()
        if not s: continue
        if s and s[0].islower():
            issues.append(f'Sentence {i+1}: Starts with lowercase: "{s[:40]}..."')
        if len(s.split()) > 40:
            issues.append(f'Sentence {i+1}: Very long sentence ({len(s.split())} words)')
    # missing space after punctuation
    for m in re.finditer(r'[,;:.!?][A-Za-z]', text):
        issues.append(f'Pos {m.start()}: Missing space after "{m.group()[0]}"')
    # double spaces
    for m in re.finditer(r'  +', text):
        issues.append(f'Pos {m.start()}: Multiple spaces')
    return issues

class App(Gtk.Window):
    def __init__(self):
        super().__init__(title='Grammar Checker')
        self.set_default_size(600, 480)
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        vbox.set_margin_top(8); vbox.set_margin_bottom(8)
        vbox.set_margin_start(8); vbox.set_margin_end(8)
        self.add(vbox)
        vbox.add(Gtk.Label(label='Input text:', xalign=0))
        sw1 = Gtk.ScrolledWindow(); sw1.set_size_request(-1, 180)
        self.inp = Gtk.TextView(); self.inp.set_wrap_mode(Gtk.WrapMode.WORD)
        sw1.add(self.inp)
        vbox.pack_start(sw1, False, False, 0)
        btn = Gtk.Button(label='Check Grammar')
        btn.connect('clicked', self.check)
        vbox.pack_start(btn, False, False, 0)
        self.count_lbl = Gtk.Label(label='', xalign=0)
        vbox.pack_start(self.count_lbl, False, False, 0)
        sw2 = Gtk.ScrolledWindow()
        self.out = Gtk.TextView(); self.out.set_editable(False)
        self.out.set_wrap_mode(Gtk.WrapMode.WORD)
        sw2.add(self.out)
        vbox.pack_start(sw2, True, True, 0)
    def check(self, *_):
        buf = self.inp.get_buffer()
        text = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), False)
        issues = check_grammar(text)
        ob = self.out.get_buffer()
        if issues:
            self.count_lbl.set_markup(f'<span foreground="red"><b>{len(issues)} issue(s) found</b></span>')
            ob.set_text('\n'.join(f'⚠  {i}' for i in issues))
        else:
            self.count_lbl.set_markup('<span foreground="green"><b>No issues found!</b></span>')
            ob.set_text('✓ Text looks good.')

win = App()
win.connect('destroy', Gtk.main_quit)
win.show_all()
Gtk.main()
