#!/usr/local/bin/python3.12

import requests
import argparse
import json
import toml
import datetime

class FatalError(Exception):
    """Custom exception for fatal errors."""
    def __init__(self, message, original_exception=None):
        super().__init__(message)
        self.original_exception = original_exception

    def __str__(self):
        if self.original_exception:
            return f"{super().__str__()} (original exception: {self.original_exception})"
        return super().__str__()


# Load configuration from file
try:
    config = toml.load("config.toml")
    JIRA_URL = config["JIRA"]["JIRA_URL"]
    API_TOKEN = config["JIRA"]["API_TOKEN"]
    keywords = config["keyword"]
    EMAIL = config["user"]["email"]
    DAILY_HOURS = config.get("user", {}).get("daily_hours", 8.0)
    PREHOLIDAY_REDUCTION = config.get("user", {}).get("preholiday_reduction", 1.0)
except KeyError as e:
    print(f"Missing configuration key: {e}")
    exit(1)
except FileNotFoundError:
    config_template = """
[JIRA]
JIRA_URL = "https://your-jira-instance.atlassian.net" # Replace with your JIRA URL
API_TOKEN = "your-api-token"                          # Replace with your JIRA API Token

[user]
email = "your-email@example.com"                      # Your email address (used for git inspect)
daily_hours = 8.0                                     # Contract daily working hours
preholiday_reduction = 1.0                            # Hours subtracted from a pre-holiday day

# Define keywords for common tasks (optional)
[keyword.meeting]
ticket = "INTERNAL-123"
account = "001-GEN"
component = "Meetings"

[keyword.training]
ticket = "INTERNAL-456"
account = "001-GEN"
component = "Learning"

[keyword.scrum]
ticket = "INTERNAL-123"
account = "001-GEN"
component = "Meetings"

# Define default account/component for specific JIRA projects (optional)
[project.PROJ]
account = "002-PROJ"
component = "Project"

# Automatic worklogs (optional)
# day_of_week can be a comma-separated list of days (e.g., "Monday,Wednesday,Friday")
# or ranges (e.g., "Mon-Fri"). Short names are also supported (e.g. "Mon", "Tue").
# [[automatic]]
# day_of_week = "Mon-Thu"
# worklogs = ["0.25 scrum \"Daily Scrum\""]
#
# [[automatic]]
# day_of_week = "Friday"
# worklogs = [
#   "0.25 scrum \"Daily Scrum\"",
#   "1.0 scrum \"Sprint Planning\"",
#   "0.5 scrum \"Sprint Retro\""
# ]
"""
    print("Configuration file 'config.toml' not found.")
    print("")
    print("Please create 'config.toml' in the same directory as the script with the following content:")
    print("-" * 40)
    print(config_template.strip())
    print("-" * 40)
    exit(1)

# Global variable for WORKER ID, fetched from JIRA
WORKER = None

def get_current_user_worker_id():
    """Fetches the current user's JIRA key (worker ID) using the API token."""
    url = f"{JIRA_URL}/rest/api/2/myself"
    headers = {
        "Accept": "application/json",
        "Authorization": f"Bearer {API_TOKEN}"
    }
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        user_info = response.json()
        return user_info.get("key")
    except requests.exceptions.RequestException as e:
        raise FatalError("Failed to retrieve current user information from JIRA", e)
    except KeyError:
        raise FatalError("Could not find 'key' in JIRA user information response")

def get_working_days(start_date, end_date):
    url = f"{JIRA_URL}/rest/tempo-timesheets/4/private/days/search"
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_TOKEN}"
    }
    data = {
        "from": start_date,
        "to": end_date,
        "userKeys": [WORKER]
    }

    try:
        datetime.datetime.strptime(start_date, "%Y-%m-%d")
        datetime.datetime.strptime(end_date, "%Y-%m-%d")
    except ValueError as e:
        print(f"Invalid date format: {e}")
        return {}

    response = requests.post(url, headers=headers, data=json.dumps(data))

    if response.status_code != 200:
        raise FatalError(f"Failed to retrieve working days: {response.status_code} {response.text}", response)

    days_info = response.json()
    if not days_info:
        raise FatalError(f"Tempo returned no day data for {WORKER}")

    days = days_info[0]['days']
    holidays = {d['date'] for d in days if d['type'] == "HOLIDAY"}

    required = {}
    for d in days:
        if d['type'] != "WORKING_DAY":
            continue
        date = d['date']
        hours = DAILY_HOURS
        next_day = (datetime.datetime.strptime(date, "%Y-%m-%d")
                    + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
        if next_day in holidays:
            hours -= PREHOLIDAY_REDUCTION
        required[date] = round(hours, 2)
    return required

def get_existing_worklogs_for_date(date):
    url = f"{JIRA_URL}/rest/tempo-timesheets/4/worklogs/search"
    headers = {
        "Accept": "application/json",
        "Authorization": f"Bearer {API_TOKEN}",
        "Content-Type": "application/json"
    }
    data = {
        "from": date,
        "to": date,
        "includeSubtasks": True,
        "worker": [ WORKER ]
    }
    
    try:
        response = requests.post(url, headers=headers, data=json.dumps(data))
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        raise FatalError(f"Failed to retrieve worklogs for {date}", e)

def delete_worklogs(worklogs):
    headers = {
        "Accept": "application/json",
        "Authorization": f"Bearer {API_TOKEN}",
        "Content-Type": "application/json"
    }

    for worklog in worklogs:
        delete_url = f"{JIRA_URL}/rest/tempo-timesheets/4/worklogs/{worklog['tempoWorklogId']}"
        delete_response = requests.delete(delete_url, headers=headers)
        if delete_response.status_code in [200, 204]:
            print(f"Deleted worklog {worklog['tempoWorklogId']}.")
        else:
            raise FatalError(f"Failed to delete worklog {worklog['tempoWorklogId']}: {delete_response.status_code} {delete_response.text}", delete_response)

def add_worklog(ticket, hours, account, component, date, comment=""):

    url = f"{JIRA_URL}/rest/tempo-timesheets/4/worklogs"
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_TOKEN}"
    }
    time_spent = int(hours * 3600)  # Convert hours to seconds
    
    data = {
        "originTaskId": ticket,
        "timeSpentSeconds": time_spent,
        "worker": WORKER,
        "comment": comment,
        "attributes": {
            "_Initiative_": {
                "name": "Account",
                "workAttributeId": 1,
                "value": account
            },
            "_Componenttool_": {
                "name": "Component/tool",
                "workAttributeId": 2,
                "value": component
            }
        },
        "started": date,
        "remainingEstimate": 0,
        "includeNonWorkingDays": False
    }
    
    try:
        response = requests.post(url, headers=headers, data=json.dumps(data))
        response.raise_for_status()
        print(f"{date} Logged {hours}h to {ticket}, account {account}, component {component}, \"{comment}\".")
    except requests.exceptions.RequestException as e:
        raise FatalError(f"Failed to log work for {ticket} on {date}: {e}", e)

def parse_day_of_week(day_of_week_str):
    """
    Parses a day of week string which can contain comma-separated values,
    ranges, and short names.
    Returns a set of lowercase full day names.
    """
    days_of_week_map = {
        "mon": "monday", "tue": "tuesday", "wed": "wednesday",
        "thu": "thursday", "fri": "friday", "sat": "saturday",
        "sun": "sunday",
        "monday": "monday", "tuesday": "tuesday", "wednesday": "wednesday",
        "thursday": "thursday", "friday": "friday", "saturday": "saturday",
        "sunday": "sunday"
    }
    ordered_days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
    
    selected_days = set()
    parts = day_of_week_str.lower().replace(" ", "").split(',')
    
    for part in parts:
        if '-' in part:
            try:
                start_day_str, end_day_str = part.split('-', 1)
                start_day = days_of_week_map.get(start_day_str)
                end_day = days_of_week_map.get(end_day_str)
                
                if start_day and end_day:
                    start_index = ordered_days.index(start_day)
                    end_index = ordered_days.index(end_day)
                    if start_index <= end_index:
                        for i in range(start_index, end_index + 1):
                            selected_days.add(ordered_days[i])
            except ValueError:
                continue # ignore malformed ranges
        else:
            day = days_of_week_map.get(part)
            if day:
                selected_days.add(day)
                
    return selected_days

def generate_template(month):
    # Determine the first and last day of the month
    start_date = f"{month}-01"
    end_date = (datetime.datetime.strptime(start_date, "%Y-%m-%d") + datetime.timedelta(days=31)).replace(day=1) - datetime.timedelta(days=1)
    end_date = end_date.strftime("%Y-%m-%d")

    # Get working days for the month
    working_days = get_working_days(start_date, end_date)

    # Load automatic worklogs from config
    automatic_worklogs = config.get("automatic", [])

    # Generate template
    template_lines = []
    for day in sorted(working_days):
        base = working_days[day]
        day_dt = datetime.datetime.strptime(day, "%Y-%m-%d")
        day_of_week_name = day_dt.strftime('%A')
        
        day_lines = []
        total_auto_hours = 0.0

        for auto_log in automatic_worklogs:
            day_of_week_spec = auto_log.get('day_of_week', '')
            applicable_days = parse_day_of_week(day_of_week_spec)
            if day_of_week_name.lower() in applicable_days:
                for worklog_line in auto_log.get('worklogs', []):
                    if not worklog_line:
                        continue
                    day_lines.append(f"{day} {worklog_line}")
                    try:
                        hours_str = worklog_line.split()[0]
                        hours = float(hours_str)
                        if not hours_str.startswith('+'):
                            total_auto_hours += hours
                    except (ValueError, IndexError):
                        print(f"Warning: could not parse hours from automatic worklog: '{worklog_line}'. Skipping for hour calculation.")
        
        if day_lines:
            remaining_hours = base - total_auto_hours
            if remaining_hours > 0:
                day_lines.append(f"{day} {remaining_hours:.1f} jira-ticket \"comment\"")
            elif remaining_hours < 0:
                print(f"Warning: non-overtime automatic worklogs on {day} ({day_of_week_name}) exceed {base} hours.")
            template_lines.extend(day_lines)
        else:
            template_lines.append(f"{day} {base} jira-ticket \"comment\"")

    # Output template
    template_content = (
        "# date hours jira-ticket [\"comment\"] [account:<account>] [component:<component>]\n"
        "# or\n"
        "# date hours <keyword> [\"comment\"] [account:<account>] [component:<component>]\n"
        "#\n"
        "# where <keyword> is one of: interview, scrum, training, etc\n"
        "# See the definitions of keywords in config.toml\n\n"
        + "\n".join(template_lines)
    )
    
    file_name = f"{month}.jira"
    try:
        with open(file_name, "x") as f:
            f.write(template_content)
        print(f"Template written to {file_name}")
    except FileExistsError:
        print(f"File {file_name} already exists. Template not written to avoid overwriting.")

def parse_worklog_line(line):
    parts = line.split()
    if len(parts) < 3:
        raise ValueError(f"Invalid entry: {line}")
    
    date = parts[0]
    hours_str = parts[1]
    is_overtime = hours_str.startswith('+')
    hours = float(hours_str)
    ticket_or_keyword = parts[2]
    project_key = ticket_or_keyword.split('-')[0] if '-' in ticket_or_keyword else None

    if project_key and project_key in config.get("project", {}):
        ticket = ticket_or_keyword
        project_config = config["project"][project_key]
        account = project_config["account"]
        component = project_config["component"]
    elif ticket_or_keyword.lower() in keywords:
        keyword = parts[2].lower()
        ticket = keywords[keyword]["ticket"]
        account = keywords[keyword]["account"]
        component = keywords[keyword]["component"]
    else:
        raise ValueError(f"Unknown project or keyword in entry: {line}.")

    # Parse comment and overrides
    comment_parts = []
    override_parts = []
    if len(parts) > 3:
        for part in parts[3:]:
            if part.startswith("account:") or part.startswith("component:"):
                override_parts.append(part)
            else:
                comment_parts.append(part)
    comment = " ".join(comment_parts).strip('"')

    # Apply overrides
    for op in override_parts:
        if op.startswith("account:"):
            account = op.split(":", 1)[1]
        elif op.startswith("component:"):
            component = op.split(":", 1)[1]

    return date, hours, ticket, account, component, comment, is_overtime

def validate_worklogs(all_dates, daily_hours, working_days):
    valid_dates = []
    for date in sorted(all_dates):
        total_hours = daily_hours.get(date, 0)
        if date in working_days:
            expected = working_days[date]
            if total_hours != expected:
                raise ValueError(f"Total non-overtime logged hours for {date} is {total_hours}, expected {expected}. Stopping worklog application.")
            valid_dates.append(date)
        else:
            if total_hours != 0:
                raise ValueError(f"Non-overtime hours logged on non-working day {date} ({total_hours} hours). Stopping worklog application.")
            else:
                valid_dates.append(date)
    return valid_dates

def process_worklog_file(file_path):
    dates_processed = {}
    daily_hours = {}
    
    with open(file_path, "r") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):  # Skip empty lines and comments
                continue
            try:
                date, hours, ticket, account, component, comment, is_overtime = parse_worklog_line(line)
            except ValueError as e:
                print(f"Error processing line: {line}. {e}")
                return

            # Accumulate hours for each date
            if date not in daily_hours:
                daily_hours[date] = 0
            if not is_overtime:
                daily_hours[date] += hours
            
            # Store worklog details for later processing
            if date not in dates_processed:
                dates_processed[date] = []
            dates_processed[date].append((ticket, float(hours), account, component, comment))
    
    # Determine the date range for validation
    all_dates = list(dates_processed.keys())
    if all_dates:
        start_date = min(all_dates)
        end_date = max(all_dates)
        working_days = get_working_days(start_date, end_date)
    else:
        working_days = set()

    # Validate worklogs, ensuring no worklogs on non-working days
    valid_dates = validate_worklogs(all_dates, daily_hours, working_days)
    
    # Process worklogs only for valid dates
    for date in valid_dates:
        existing_worklogs = get_existing_worklogs_for_date(date)
        new_worklogs = dates_processed[date]

        # Compare existing and new worklogs by ticket, hours, account, component, and comment
        existing_worklogs_list = sorted([
            (
                wl['issue']['key'],
                wl['timeSpentSeconds'] / 3600,
                wl['attributes']['_Initiative_']['value'],
                wl['attributes']['_Componenttool_']['value'],
                "" if wl['comment'] == f"Working on issue {wl['issue']['key']}" else wl['comment']
            )
            for wl in existing_worklogs
        ])
        new_worklogs_list = sorted([(ticket, hours, account, component, comment) for ticket, hours, account, component, comment in new_worklogs])

        if existing_worklogs_list != new_worklogs_list:
            # Only proceed with deletion/addition if there are changes
            if existing_worklogs:
                # Print differences
                existing_set = set(existing_worklogs_list)
                new_set = set(new_worklogs_list)
                print(f"Differences found for {date}:")
                to_delete = existing_set - new_set
                to_add = new_set - existing_set
                if to_delete:
                    print("Worklogs to be deleted:")
                    for worklog in to_delete:
                        print(worklog)
                if to_add:
                    print("Worklogs to be added:")
                    for worklog in to_add:
                        print(worklog)

                if to_delete:
                    confirm = input(f"Are you sure you want to delete existing worklogs for {date} and apply changes? (yes/no): ").strip().lower()
                    if confirm == 'yes':
                        delete_worklogs(existing_worklogs)
                for ticket, hours, account, component, comment in new_worklogs:
                    add_worklog(ticket, hours, account, component, date, comment)
            else:
                # No existing worklogs, just add the new ones
                print(f"No existing worklogs for {date}. Adding new worklogs:")
                for worklog in new_worklogs_list:
                    print(worklog)
                for ticket, hours, account, component, comment in new_worklogs:
                    add_worklog(ticket, hours, account, component, date, comment)
        else:
            print(f"No changes in worklogs for {date}. Skipping update.")

def validate_worklog_file(file_path):
    daily_hours = {}
    all_dates = set()
    
    with open(file_path, "r") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):  # Skip empty lines and comments
                continue
            try:
                date, hours, ticket, account, component, comment, is_overtime = parse_worklog_line(line)
            except ValueError as e:
                print(f"Error processing line: {line}. {e}")
                return

            all_dates.add(date)
            # Accumulate hours for each date
            if not is_overtime:
                if date not in daily_hours:
                    daily_hours[date] = 0
                daily_hours[date] += hours
    
    # Determine the date range for validation
    if all_dates:
        start_date = min(all_dates)
        end_date = max(all_dates)
        working_days = get_working_days(start_date, end_date)
    else:
        working_days = set()

    # Validate worklogs, ensuring no worklogs on non-working days
    try:
        validate_worklogs(sorted(all_dates), daily_hours, working_days)
        print("Worklogs are valid.")
    except ValueError as e:
        print(f"Validation error: {e}")

def inspect_git_repo(repo_path):
    import subprocess

    # Get the list of commits authored by the user
    try:
        result = subprocess.run(
            ["git", "-C", repo_path, "log", "--author", EMAIL, "--pretty=format:%H %ad %s", "--date=short"],
            capture_output=True,
            text=True,
            check=True
        )
        commits = result.stdout.strip().split("\n")
    except subprocess.CalledProcessError as e:
        raise FatalError(f"Failed to retrieve commits from Git repository: {e}", e)

    # Generate worklog from commits
    worklog_lines = []
    for commit in commits:
        commit_hash, date, message = commit.split(" ", 2)
        worklog_lines.append(f"{date} {DAILY_HOURS} {commit_hash} \"{message}\"")

    # Output worklog
    worklog_content = "\n".join(worklog_lines)
    print("Generated worklog based on commits:")
    print(worklog_content)


if __name__ == "__main__":
    try:
        # Fetch the WORKER ID after loading config and before parsing args
        WORKER = get_current_user_worker_id()
        if not WORKER:
            raise FatalError("Could not determine WORKER ID from JIRA.")
        print(f"Operating as JIRA user: {WORKER}")

        parser = argparse.ArgumentParser(description="Manage JIRA worklogs using Tempo.")
        subparsers = parser.add_subparsers(dest="command", required=True)

        # Apply command
        apply_parser = subparsers.add_parser("apply", help="Apply worklogs from a file")
        apply_parser.add_argument("file", help="Path to the text file containing worklog entries")

        # Generate command
        generate_parser = subparsers.add_parser("generate", help="Generate a worklog template for a month")
        generate_parser.add_argument("month", help="Month in the format YYYY-MM")

        # Inspect command
        inspect_parser = subparsers.add_parser("inspect", help="Inspect a Git repository and generate worklog based on commits")
        inspect_parser.add_argument("repo_path", help="Path to the Git repository")

        # Validate command
        validate_parser = subparsers.add_parser("validate", help="Validate worklogs from a file without applying them")
        validate_parser.add_argument("file", help="Path to the text file containing worklog entries")

        args = parser.parse_args()

        if args.command == "help":
            parser.print_help()
            exit(0)

        if args.command == "apply":
            process_worklog_file(args.file)
        elif args.command == "validate":
            validate_worklog_file(args.file)
        elif args.command == "generate":
            generate_template(args.month)
    except FatalError as e:
        print(f"Fatal error: {e}")
        exit(1)
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        exit(1)

