"""Tag support tickets with simple keyword scores.

This module is a separate .py file so main.py can import its functions.
That split is the “modules” idea: one file holds the rules, another file
runs them.
"""

# Each tag name maps to a list of words or short phrases to look for.
KEYWORD_LISTS = {
    "login": ["login", "password", "credentials", "sign in", "reset"],
    "billing": ["invoice", "charge", "payment", "refund", "billing"],
    "shipping": ["shipping", "delivery", "package", "tracking", "shipment"],
    "bug": ["crash", "error", "bug", "broken", "exception"],
    "feature": ["feature", "request", "would like", "enhancement"],
}

# Check tags in this order. If two tags tie, the earlier one wins.
TAG_ORDER = ["login", "billing", "shipping", "bug", "feature"]

DEFAULT_TAG = "general"


def combine_text(ticket):
    """Build one lowercase string from the subject and body."""
    subject = ticket["subject"]
    body = ticket["body"]
    combined = subject + " " + body
    return combined.lower()


def score_tag(text, keywords):
    """Count how many keywords from the list appear in the text."""
    score = 0
    for word in keywords:
        if word in text:
            score = score + 1
    return score


def choose_tag(ticket):
    """Return the tag with the highest keyword score (or general)."""
    text = combine_text(ticket)
    best_tag = DEFAULT_TAG
    best_score = 0

    for tag in TAG_ORDER:
        keywords = KEYWORD_LISTS[tag]
        score = score_tag(text, keywords)
        if score > best_score:
            best_score = score
            best_tag = tag

    return best_tag


def tag_ticket(ticket):
    """Return a new dict that copies the ticket and adds a tag key."""
    tagged = {}
    for key in ticket:
        tagged[key] = ticket[key]
    tagged["tag"] = choose_tag(ticket)
    return tagged


def tag_all(tickets):
    """Tag every ticket in a list and return a new list."""
    tagged_list = []
    for ticket in tickets:
        tagged_ticket = tag_ticket(ticket)
        tagged_list.append(tagged_ticket)
    return tagged_list


def count_by_tag(tagged_tickets):
    """Return a dict of tag -> how many tickets have that tag."""
    counts = {}
    for ticket in tagged_tickets:
        tag = ticket["tag"]
        if tag not in counts:
            counts[tag] = 0
        counts[tag] = counts[tag] + 1
    return counts
