#!/usr/bin/env python3
# timesheet - log time spent on tasks, with a daily summary
# Usage: timesheet start TASK | timesheet stop [--note TEXT] | timesheet status
#        timesheet summary [--date YYYY-MM-DD] | timesheet list [--date D]
#   Entries live in a tab-separated log (default ~/.local/share/fileutils/timesheet.tsv).
#   Only one task runs at a time; starting a new one stops the current task.
import argparse, os, sys
from datetime import datetime, date

DEFAULT_FILE = os.path.expanduser("~/.local/share/fileutils/timesheet.tsv")

def read_entries(path):
    entries = []
    if os.path.exists(path):
        for line in open(path):
            parts = line.rstrip("\n").split("\t")
            if len(parts) >= 2:
                entries.append(parts)
    return entries

def write_entries(path, entries):
    d = os.path.dirname(path)
    if d:
        os.makedirs(d, exist_ok=True)
    with open(path, "w") as f:
        for e in entries:
            f.write("\t".join(e) + "\n")

def open_entry(entries):
    for e in reversed(entries):
        if len(e) == 2:  # start, task (no end yet)
            return e
    return None

def fmt_hms(seconds):
    h, rem = divmod(int(seconds), 3600)
    m, s = divmod(rem, 60)
    return f"{h}:{m:02d}:{s:02d}"

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        f = os.path.join(d, "ts.tsv")
        now = datetime(2026, 12, 3, 9, 0)
        entries = [["2026-12-03T09:00:00", "coding"],
                   ["2026-12-03T10:30:00", "coding", "2026-12-03T11:00:00"]]
        write_entries(f, entries)
        back = read_entries(f)
        assert len(back) == 2 and back[1][1] == "coding"
        secs = (datetime.fromisoformat(back[1][2]) - datetime.fromisoformat(back[1][0])).total_seconds()
        assert secs == 1800 and fmt_hms(secs) == "0:30:00"
        assert open_entry(back) is not None  # first row still open
        print("timesheet selftest: ok (log round-trip, 30m duration, open-task detect)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="timesheet",
        description="Log time spent on tasks, with a daily summary.")
    p.add_argument("cmd", nargs="?", choices=["start", "stop", "status", "summary", "list"],
                  help="start TASK | stop | status | summary | list")
    p.add_argument("task", nargs="?", help="task name for start")
    p.add_argument("--note", default="", help="note to attach (stop)")
    p.add_argument("--date", help="date for summary/list (default today)")
    p.add_argument("--file", default=DEFAULT_FILE, help="log file")
    p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    if not a.cmd:
        p.error("a command is required: start, stop, status, summary, list")
    entries = read_entries(a.file)
    now = datetime.now()
    if a.cmd == "start":
        if not a.task:
            p.error("start needs a TASK name")
        cur = open_entry(entries)
        if cur:
            cur.append(now.isoformat(timespec="seconds"))
            print(f"stopped {cur[1]!r} (was running since {cur[0]})")
        entries.append([now.isoformat(timespec="seconds"), a.task])
        write_entries(a.file, entries)
        print(f"started {a.task!r} at {now:%H:%M}")
    elif a.cmd == "stop":
        cur = open_entry(entries)
        if not cur:
            print("timesheet: no task is running", file=sys.stderr); return 1
        cur.append(now.isoformat(timespec="seconds"))
        if a.note:
            cur.append(a.note)
        write_entries(a.file, entries)
        secs = (now - datetime.fromisoformat(cur[0])).total_seconds()
        print(f"stopped {cur[1]!r}: {fmt_hms(secs)}")
    elif a.cmd == "status":
        cur = open_entry(entries)
        if not cur:
            print("no task running")
        else:
            secs = (now - datetime.fromisoformat(cur[0])).total_seconds()
            print(f"running {cur[1]!r} for {fmt_hms(secs)} (since {cur[0][11:16]})")
    else:  # summary / list
        day = a.date or date.today().isoformat()
        totals = {}
        for e in entries:
            if not e[0].startswith(day):
                continue
            if len(e) < 3:
                continue
            secs = (datetime.fromisoformat(e[2]) - datetime.fromisoformat(e[0])).total_seconds()
            totals[e[1]] = totals.get(e[1], 0) + secs
            if a.cmd == "list":
                print(f"{e[0][11:16]}-{e[2][11:16]}  {e[1]}  {fmt_hms(secs)}")
        if a.cmd == "summary":
            if not totals:
                print(f"no entries for {day}")
            else:
                grand = 0
                for task, secs in sorted(totals.items(), key=lambda kv: -kv[1]):
                    print(f"{task}: {fmt_hms(secs)}")
                    grand += secs
                print(f"total: {fmt_hms(grand)}")
        cur = open_entry(entries)
        if cur and cur[0].startswith(day):
            print(f"(running now: {cur[1]!r} since {cur[0][11:16]})")
    return 0

if __name__ == "__main__":
    sys.exit(main())
