#!/usr/bin/env python3
"""hdc -- local filesystem mirror of a HedgeDoc account, organized by tag.

(Named hdc, not hd: hd already means hexdump on Debian/Ubuntu --
bsdextrautils ships it as a standard alias, and it beat us to the name.)

  hdc init [<hedgedoc-url>] [--email E] [--cookie '...'] [--dir ~/notes]
  hdc sync [--dir ~/notes] [-v] [--watch [--interval SECONDS]]
  hdc tag <note> <tag> [--dir ~/notes]
  hdc untag <note> <tag> [--dir ~/notes]

Layout created under --dir (default: ~/notes):
  .hd/config.json     server url (+ email, if you logged in), mode 0600
  .hd/cookies.json    session cookie, mode 0600 -- kept separate from
                       config.json since this is the actual credential
  .hd/state.json      what the reconciler believes is true
  .hd/problems.json   things sync noticed but can't safely fix itself
  .hd/notes/<id>.md   cached note content (read-only cache -- do not edit)
  <tag>/<title>.md     symlink into .hd/notes/<id>.md, one per tag
  untagged/<title>.md  symlink for notes with no tags

`sync` only ever pulls from HedgeDoc. `tag`/`untag` are the only commands
that write back -- they edit the note's own YAML frontmatter over the
realtime channel (there's no plain HTTP save endpoint for existing notes)
and then re-run a sync pass so the local symlinks catch up immediately.
"""
from __future__ import annotations

import argparse
import getpass
import logging
import sys
import time
from pathlib import Path
from typing import Optional

# hd_core.py/hd_client.py live in ../hd_common, shared verbatim with hd-joe
# (see hd_common/README.md) -- add it to sys.path before importing either,
# regardless of where this script is actually invoked from.
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common"))

from hd_core import (
    Config, Cookies, HedgeDocSource, LoginError, State,
    find_hd_root, login, reconcile, resolve_note_ref, update_note_tags_locally, write_tags,
)

logger = logging.getLogger("hdc")


def cmd_init(args: argparse.Namespace) -> int:
    root = Path(args.dir).expanduser()
    hd_dir = root / ".hd"
    if hd_dir.exists():
        print(f"{hd_dir} already exists -- refusing to overwrite. "
              f"Delete it yourself first if you really want to re-init.", file=sys.stderr)
        return 1

    url = args.url or input("HedgeDoc server URL: ").strip()
    if not url:
        print("A server URL is required.", file=sys.stderr)
        return 1

    email: str | None = None
    if args.cookie:
        cookie_header = args.cookie
    else:
        # Interactive login dialog: server (above), then email + password.
        email = args.email or input("Email: ").strip()
        if not email:
            print("An email address is required for login "
                  "(or pass --cookie if this server uses SSO/LDAP instead).", file=sys.stderr)
            return 1
        password = getpass.getpass("Password: ")
        try:
            cookie_header = login(url, email, password)
        except LoginError as exc:
            print(f"Login failed: {exc}", file=sys.stderr)
            return 1

    root.mkdir(parents=True, exist_ok=True)
    hd_dir.mkdir(parents=True, exist_ok=True)
    (hd_dir / "notes").mkdir(parents=True, exist_ok=True)

    config = Config(url=url.rstrip("/"), email=email)
    config.save(hd_dir)
    Cookies(header=cookie_header).save(hd_dir)

    print(f"Initialized {root}. Running first sync...")
    return _do_sync(root)


def _resolve_root(dir_arg: Optional[str]) -> Path:
    """--dir was given explicitly: use it, unchanged from before. Otherwise
    walk up from the current directory looking for .hd/ -- same discovery
    hd-joe already does -- so standing anywhere inside an hd-managed
    folder (not just its root) just works, without needing --dir spelled
    out every time. Falls back to the old hardcoded ~/notes only if that
    search finds nothing, so running these commands from somewhere
    unrelated still behaves the way it always has."""
    if dir_arg is not None:
        return Path(dir_arg).expanduser()
    found = find_hd_root(Path.cwd())
    if found is not None:
        return found
    return Path("~/notes").expanduser()


def _do_sync(root: Path) -> int:
    hd_dir = root / ".hd"
    if not hd_dir.exists():
        print(f"{hd_dir} does not exist -- run 'hdc init' first.", file=sys.stderr)
        return 1
    config = Config.load(hd_dir)
    cookies = Cookies.load(hd_dir)
    state = State.load(hd_dir)
    source = HedgeDocSource(config.url, cookies.header)
    try:
        result = reconcile(root, source, state)
    except RuntimeError as exc:
        print(str(exc), file=sys.stderr)
        return 1
    state.save(hd_dir)

    if result.notes_updated:
        print(f"Updated: {len(result.notes_updated)} note(s)")
    if result.notes_removed:
        print(f"Removed: {len(result.notes_removed)} note(s) no longer in your history")
    if result.symlinks_created:
        logger.info("Created %d symlink(s)", len(result.symlinks_created))
    if result.symlinks_removed:
        logger.info("Removed %d symlink(s)", len(result.symlinks_removed))
    if not (result.notes_updated or result.notes_removed):
        print("Up to date.")
    if result.problems:
        print(f"\n{len(result.problems)} problem(s) found:")
        for p in result.problems:
            print(f"  - {p}")
    return 0


def cmd_sync(args: argparse.Namespace) -> int:
    root = _resolve_root(args.dir)
    if not args.watch:
        return _do_sync(root)
    print(f"Watching (polling every {args.interval}s). Ctrl-C to stop.")
    try:
        while True:
            rc = _do_sync(root)
            if rc != 0:
                return rc
            time.sleep(args.interval)
    except KeyboardInterrupt:
        return 0


def _cmd_retag(args: argparse.Namespace, mutate) -> int:
    root = _resolve_root(args.dir)
    hd_dir = root / ".hd"
    if not hd_dir.exists():
        print(f"{hd_dir} does not exist -- run 'hdc init' first.", file=sys.stderr)
        return 1
    config = Config.load(hd_dir)
    cookies = Cookies.load(hd_dir)
    state = State.load(hd_dir)  # read-only here; write_tags never touches local state

    try:
        # cwd, not root: 'FOI' means the symlink named FOI in the
        # directory the user is actually standing in, '../work/FOI' the
        # one in ../work -- see resolve_note_ref's docstring.
        note_id = resolve_note_ref(root, state, args.note, cwd=Path.cwd())
    except ValueError as exc:
        print(str(exc), file=sys.stderr)
        return 1

    try:
        new_tags = write_tags(config.url, cookies.header, note_id, mutate)
    except Exception as exc:
        print(f"Could not update tags for {note_id}: {exc}", file=sys.stderr)
        return 1

    print(f"{note_id}: tags now [{', '.join(new_tags) if new_tags else '(none)'}]")
    # Apply the symlink change directly from the write's own confirmed
    # result, before the /history-driven sync below -- /history can lag a
    # just-completed write by a few seconds (HedgeDoc's DB-flush delay),
    # which left a stale symlink in place after a real 'hdc untag'. This
    # makes the CLI's own view correct immediately regardless of that;
    # _do_sync() below still runs as the general catch-all for anything
    # else that may have changed elsewhere since the last sync.
    try:
        update_note_tags_locally(root, note_id, new_tags)
    except Exception as exc:
        logger.warning("Could not apply the local symlink update directly (%s); "
                        "the sync below is still the safety net.", exc)
    print("Syncing local symlinks...")
    return _do_sync(root)  # reconcile() takes its own lock; nothing held across this call


def cmd_tag(args: argparse.Namespace) -> int:
    tag = args.tag
    return _cmd_retag(args, lambda tags: tags if tag in tags else [*tags, tag])


def cmd_untag(args: argparse.Namespace) -> int:
    tag = args.tag
    return _cmd_retag(args, lambda tags: [t for t in tags if t != tag])


def main() -> int:
    ap = argparse.ArgumentParser(prog="hdc", description=__doc__,
                                  formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("-v", "--verbose", action="store_true")
    sub = ap.add_subparsers(dest="command", required=True)

    p_init = sub.add_parser("init", help="Set up a new hd-managed folder")
    p_init.add_argument("url", nargs="?", help="HedgeDoc server URL (prompted for if omitted)")
    p_init.add_argument("--email", help="Email to log in with (prompted for if omitted and no --cookie)")
    p_init.add_argument("--cookie", help="Skip the login dialog: use this Cookie header directly "
                                          "(needed for SSO/LDAP servers with no local password login)")
    p_init.add_argument("--dir", default="~/notes", help="Target folder (default: ~/notes)")
    p_init.set_defaults(func=cmd_init)

    dir_help = ("Target folder. Default: auto-detected by walking up from the "
                "current directory looking for .hd/ (same as hd-joe), falling "
                "back to ~/notes if that finds nothing.")

    p_sync = sub.add_parser("sync", help="Pull notes and reconcile tag symlinks")
    p_sync.add_argument("--dir", default=None, help=dir_help)
    p_sync.add_argument("--watch", action="store_true", help="Keep syncing in a loop instead of once")
    p_sync.add_argument("--interval", type=float, default=30.0, help="Seconds between syncs with --watch")
    p_sync.set_defaults(func=cmd_sync)

    p_tag = sub.add_parser("tag", help="Add a tag to a note (writes to HedgeDoc)")
    p_tag.add_argument("note", help="Note id, or a path to one of its symlinks -- resolved from where "
                                     "you're standing, like any other path (bare 'Title' means the symlink "
                                     "named Title right here; '../work/Title' means the one in ../work) -- "
                                     "or, only if no symlink matches, its (unique) title anywhere")
    p_tag.add_argument("tag", help="Tag to add")
    p_tag.add_argument("--dir", default=None, help=dir_help)
    p_tag.set_defaults(func=cmd_tag)

    p_untag = sub.add_parser("untag", help="Remove a tag from a note (writes to HedgeDoc)")
    p_untag.add_argument("note", help="Note id, or a path to one of its symlinks -- resolved from where "
                                       "you're standing, like any other path (bare 'Title' means the symlink "
                                       "named Title right here; '../work/Title' means the one in ../work) -- "
                                       "or, only if no symlink matches, its (unique) title anywhere")
    p_untag.add_argument("tag", help="Tag to remove")
    p_untag.add_argument("--dir", default=None, help=dir_help)
    p_untag.set_defaults(func=cmd_untag)

    args = ap.parse_args()
    logging.basicConfig(level=logging.DEBUG if args.verbose else logging.WARNING,
                         format="%(levelname)s %(message)s")
    return args.func(args)


if __name__ == "__main__":
    raise SystemExit(main())
