#!/usr/bin/env python3
# focus - focus session tracker: start/stop, log, daily total
# Usage: focus start [LABEL] | focus stop | focus status | focus log | focus today
# Log file: $FOCUS_LOG or ~/.focus.log (JSON lines: {"start","end","label"})
import argparse, datetime, json, os, sys

def log_path():
    return os.environ.get("FOCUS_LOG") or os.path.expanduser("~/.focus.log")

def load(path):
    sessions = []
    if os.path.exists(path):
        with open(path) as f:
            for line in f:
                line = line.strip()
                if line:
                    try:
                        sessions.append(json.loads(line))
                    except json.JSONDecodeError:
                        continue
    return sessions

def save(path, sessions):
    with open(path, "w") as f:
        for s in sessions:
            f.write(json.dumps(s) + "\n")

def active(path):
    for s in load(path):
        if s.get("end") is None:
            return s
    return None

def fmt_dur(seconds):
    seconds = int(seconds)
    h, rem = divmod(seconds, 3600)
    m, s = divmod(rem, 60)
    return f"{h}h {m}m {s}s" if h else f"{m}m {s}s"

def cmd_start(path, label):
    if active(path):
        print("A focus session is already running — stop it first (focus stop).")
        return 1
    sessions = load(path)
    sessions.append({"start": datetime.datetime.now().isoformat(),
                     "end": None, "label": label or ""})
    save(path, sessions)
    print(f"Focus started at {datetime.datetime.now().strftime('%H:%M')}" +
          (f" — {label}" if label else ""))
    return 0

def cmd_stop(path):
    sessions = load(path)
    cur = next((s for s in sessions if s.get("end") is None), None)
    if not cur:
        print("No focus session is running.")
        return 1
    cur["end"] = datetime.datetime.now().isoformat()
    save(path, sessions)
    start = datetime.datetime.fromisoformat(cur["start"])
    dur = (datetime.datetime.fromisoformat(cur["end"]) - start).total_seconds()
    print(f"Focus stopped — session lasted {fmt_dur(dur)}" +
          (f" ({cur['label']})" if cur.get("label") else ""))
    return 0

def cmd_status(path):
    cur = active(path)
    if not cur:
        print("No focus session running.")
        return 0
    start = datetime.datetime.fromisoformat(cur["start"])
    elapsed = (datetime.datetime.now() - start).total_seconds()
    print(f"Focusing for {fmt_dur(elapsed)} since {start.strftime('%H:%M')}" +
          (f" — {cur['label']}" if cur.get("label") else ""))
    return 0

def cmd_log(path):
    sessions = load(path)
    if not sessions:
        print("No focus sessions logged yet.")
        return 0
    for s in sessions:
        start = datetime.datetime.fromisoformat(s["start"])
        if s.get("end"):
            end = datetime.datetime.fromisoformat(s["end"])
            dur = fmt_dur((end - start).total_seconds())
            print(f"{start.strftime('%Y-%m-%d %H:%M')}–{end.strftime('%H:%M')}  {dur}  {s.get('label','')}")
        else:
            print(f"{start.strftime('%Y-%m-%d %H:%M')}–(running)  {s.get('label','')}")
    return 0

def cmd_today(path, day=None):
    day = day or datetime.date.today()
    total = 0.0
    count = 0
    for s in load(path):
        start = datetime.datetime.fromisoformat(s["start"])
        if start.date() != day:
            continue
        if s.get("end"):
            total += (datetime.datetime.fromisoformat(s["end"]) - start).total_seconds()
            count += 1
    print(f"Focus total for {day.isoformat()}: {fmt_dur(total)} across {count} session(s)")
    return 0

def selftest():
    import tempfile
    fd, path = tempfile.mkstemp(prefix="focus-test-", suffix=".log")
    os.close(fd); os.unlink(path)
    os.environ["FOCUS_LOG"] = path
    try:
        assert cmd_start(path, "test session") == 0
        assert active(path) is not None
        assert cmd_start(path, "again") == 1  # already running
        assert cmd_status(path) == 0
        assert cmd_stop(path) == 0
        assert active(path) is None
        assert cmd_stop(path) == 1  # nothing running
        sessions = load(path)
        assert len(sessions) == 1 and sessions[0]["end"] is not None
        assert cmd_log(path) == 0
        assert cmd_today(path) == 0
        print("focus selftest OK")
    finally:
        if os.path.exists(path):
            os.unlink(path)
    return 0

def main():
    p = argparse.ArgumentParser(description="Focus session tracker: start/stop, log, daily total.")
    sub = p.add_subparsers(dest="cmd")
    sp = sub.add_parser("start", help="start a focus session"); sp.add_argument("label", nargs="?", default="")
    sub.add_parser("stop", help="stop the running session")
    sub.add_parser("status", help="show the running session")
    sub.add_parser("log", help="list all sessions")
    sub.add_parser("today", help="show today's total focus time")
    p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    path = log_path()
    if a.cmd == "start":
        return cmd_start(path, a.label)
    if a.cmd == "stop":
        return cmd_stop(path)
    if a.cmd == "status":
        return cmd_status(path)
    if a.cmd == "log":
        return cmd_log(path)
    if a.cmd == "today":
        return cmd_today(path)
    p.print_help()
    return 0

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