#!/usr/bin/env python3

import argparse
import csv
import re
import shutil
import sys
import textwrap
from datetime import datetime
from typing import NamedTuple


class Clipping(NamedTuple):
    title: str
    body: str


def open_clippings_txt(path, mode):
    newline = None
    if "a" in mode or "w" in mode:
        newline = "\r\n"
    return open(path, mode=mode, encoding="utf-8-sig", newline=newline)  # noqa: PTH123


def each_clipping():
    title = None
    body = []
    for line in open_clippings_txt("My Clippings.txt", mode="r"):
        if title is None:
            title = line
        else:
            body.append(line)

        if line == "==========\n":
            if title.strip() == "":
                print("EMPTY: " + "".join(body))
            yield Clipping(title, "".join(body))
            title = None
            body = []


def on_list():
    seen = set()
    for clip in each_clipping():
        if clip.title not in seen:
            seen.add(clip.title)
            print(clip.title.rstrip())


def on_export(args):
    titles = {}
    for clip in each_clipping():
        if args.pattern in clip.title:
            if clip.title not in titles:
                clippings = []
                titles[clip.title] = clippings
            else:
                clippings = titles[clip.title]

            clippings.append(clip)

    if args.format == "csv":
        export_csv(titles)
    else:
        export_markdown(titles)


def export_markdown(titles):
    first_title = True
    for title, clippings in titles.items():
        if first_title:
            first_title = False
        else:
            print()

        print("### {}".format(title))

        for clipping in clippings:
            body = clipping.body.split("\n", 2)[2]
            body = body.rsplit("\n", 2)[0]
            print("-   {}".format(textwrap.indent(body, "    ")[4:]))
            print()


META_RE = re.compile(r".*Your (Highlight|Note) on page (\d+).*Added on [a-zA-Z]+, (.*)")
METAL_RE = re.compile(
    r".*Your (Highlight|Note) on Location (\d+).*Added on [a-zA-Z]+, (.*)"
)


def split_title_author(line):
    left_count = 1
    last_left_paren = line.rfind("(")
    while left_count < line.count(")", last_left_paren):
        left_count += 1
        last_left_paren = line.rfind("(", 0, last_left_paren)

    title = line[0 : last_left_paren - 1]
    author = " & ".join(line[last_left_paren + 1 : -2].split(";"))

    return (title, author)


def parse_meta_time(text):
    time = datetime.datetime.strptime(text, "%B %d, %Y %I:%M:%S %p")
    return time.strftime("%Y-%m-%d %H:%M:%S")


def export_csv(titles):
    w = csv.writer(sys.stdout, delimiter=",", quotechar='"')
    w.writerow(["Highlight", "Title", "Author", "Note", "Location", "Date"])

    for title, clippings in titles.items():
        title, author = split_title_author(title)  # noqa: PLW2901

        prev_highlight = None
        prev_end_page = None
        prev_note = None

        for clipping in clippings:
            parts = clipping.body.split("\n", 2)
            meta = parts[0]
            body = parts[2]
            body = body.rsplit("\n", 2)[0]

            meta_match = META_RE.match(meta)
            if meta_match is None:
                meta_match = METAL_RE.match(meta)
            if meta_match is None:
                print("Unknown meta: {}".format(meta), file=sys.stderr)
            # 0 - type, 1 - page, 2 - date
            meta_fields = meta_match.groups()

            time = parse_meta_time(meta_fields[2])

            page = meta_fields[1]
            prev_end_page = page

            if meta_fields[0] == "Highlight":
                if prev_note is not None:
                    if prev_note[0] == page:
                        w.writerow([body, title, author, prev_note[1], page, time])
                        prev_note = None
                    else:
                        print(
                            "The note location and callout do not match: #{} {}".format(
                                prev_note[0], prev_note[1]
                            ),
                            file=sys.stderr,
                        )
                        sys.exit(1)
                else:
                    if prev_highlight is not None:
                        w.writerow(prev_highlight)

                    prev_highlight = [body, title, author, "", page, time]
            else:
                page = meta_fields[1]
                if page != prev_end_page:
                    if prev_note is not None:
                        print(
                            "The note location and callout do not match: #{} {}".format(
                                prev_note[0], prev_note[1]
                            ),
                            file=sys.stderr,
                        )
                        sys.exit(1)
                    prev_note = [page, body]
                else:
                    prev_highlight[3] = body

                if prev_highlight is not None:
                    w.writerow(prev_highlight)
                    prev_highlight = None
                    prev_end_page = None

        if prev_highlight is not None:
            w.writerow(prev_highlight)


def on_archive(args):
    keep = []
    seen = set()
    with open_clippings_txt("archive.bak", mode="a") as archive:
        for clip in each_clipping():
            if args.pattern in clip.title:
                if clip.title not in seen:
                    seen.add(clip.title)
                    print("Archive {}".format(clip.title.rstrip()))
                archive.write(clip.title)
                archive.write(clip.body)
            else:
                keep.append(clip)

    shutil.copy("My Clippings.txt", "backup.bak")
    with open_clippings_txt("My Clippings.txt", mode="w") as orig:
        for clip in keep:
            if clip.title not in seen:
                seen.add(clip.title)
                print("Keep {}".format(clip.title.rstrip()))
            orig.write(clip.title)
            orig.write(clip.body)


parser = argparse.ArgumentParser(description="Kindle Clippings Cli")
subparsers = parser.add_subparsers(help="sub-command help")

parser_list = subparsers.add_parser("list", help="List titles.")
parser_list.set_defaults(func=on_list)
parser_archive = subparsers.add_parser(
    "archive", help="extract matching titles and append them to archive.bak"
)
parser_archive.add_argument("pattern", help="archive titles matching the pattern")
parser_archive.set_defaults(func=on_archive)
parser_export = subparsers.add_parser(
    "export", help="export matching titles as markdown"
)
parser_export.add_argument(
    "-f",
    "--format",
    help="choose export format (default: markdown)",
    choices=["markdown", "csv"],
    default="markdown",
)
parser_export.add_argument("pattern", help="export titles matching the pattern")
parser_export.set_defaults(func=on_export)

args = parser.parse_args()
args.func(args)
