"""Load tickets, tag them, print a summary, and save JSON.

Pipeline (the steps in order):
1. Read data/tickets.json (a list of dicts).
2. Ask tagger.py to score keywords and pick a tag.
3. Print each ticket and a count-by-tag table.
4. Write output/tagged_tickets.json.
"""

import json
from pathlib import Path

import tagger

KNOWN_TAGS = ["login", "billing", "shipping", "bug", "feature", "general"]


def tutorial_folder():
    """The folder that contains this file."""
    return Path(__file__).resolve().parent


def load_tickets(path):
    """Read JSON and return a list of ticket dicts."""
    text = path.read_text(encoding="utf-8")
    tickets = json.loads(text)
    return tickets


def save_tagged(path, tagged_tickets):
    """Write the tagged list as pretty JSON."""
    path.parent.mkdir(exist_ok=True)
    text = json.dumps(tagged_tickets, indent=2)
    path.write_text(text + "\n", encoding="utf-8")


def print_ticket_list(tagged_tickets):
    print("Tagged tickets")
    print("--------------")
    for ticket in tagged_tickets:
        ticket_id = ticket["id"]
        tag = ticket["tag"]
        subject = ticket["subject"]
        print(str(ticket_id) + ". [" + tag + "] " + subject)


def print_counts(counts):
    print("Count by tag")
    print("------------")
    total = 0
    for tag in KNOWN_TAGS:
        n = 0
        if tag in counts:
            n = counts[tag]
        total = total + n
        print(tag + ": " + str(n))
    print("total: " + str(total))


def main():
    folder = tutorial_folder()
    input_path = folder / "data" / "tickets.json"
    output_path = folder / "output" / "tagged_tickets.json"

    if not input_path.exists():
        print("Could not find " + str(input_path))
        print("Run this first: python generate_data.py")
        return

    tickets = load_tickets(input_path)
    tagged_tickets = tagger.tag_all(tickets)
    counts = tagger.count_by_tag(tagged_tickets)

    print_ticket_list(tagged_tickets)
    print("")
    print_counts(counts)
    print("")

    save_tagged(output_path, tagged_tickets)
    print("Wrote " + str(len(tagged_tickets)) + " tagged tickets to " + str(output_path))


if __name__ == "__main__":
    main()
