# karyab — make is the single interface for install, config, and running.
#
#   make setup     one-shot: install + create config/secrets + init database
#   make start     launch the web UI → http://127.0.0.1:16666
#   make config    edit your profile + secrets
#   make run       fetch -> rank -> digest
#   make help      list everything
#
# Everything runs inside a local .venv that make creates and owns.

PYTHON    ?= python3
CONTAINER ?= podman
VENV   := .venv
BIN    := $(VENV)/bin
PY     := $(BIN)/python
PIP    := $(BIN)/pip
KARYAB := $(BIN)/karyab

# Resolve the XDG config dir via the installed package (empty until installed).
CONFIG_DIR = $(shell $(PY) -c "import karyab.config as c; print(c.config_dir())" 2>/dev/null)
EDITOR    ?= vi

# systemd user-unit locations
SYSTEMD_USER_DIR := $(HOME)/.config/systemd/user

.PHONY: help
help:
	@echo "karyab — job-hunting automation"
	@echo ""
	@echo "Getting started:"
	@echo "  make setup            guided one-shot: deps, db, config, email auth, first fetch"
	@echo "  make install          install runtime deps into .venv"
	@echo ""
	@echo "App (web UI):"
	@echo "  make start            build + launch the web UI → http://127.0.0.1:16666"
	@echo "  make stop             stop the web UI"
	@echo "  make logs             tail the web UI logs"
	@echo ""
	@echo "Run (pipeline):"
	@echo "  make run              fetch → rank → digest (the daily cycle)"
	@echo "  make fetch            fetch + store postings from enabled sources"
	@echo "  make rank             score stored jobs for fit"
	@echo "  make digest           render the markdown digest"
	@echo "  make followups        list applications gone quiet"
	@echo "  make apply JOB=<id>   mark a job as applied"
	@echo ""
	@echo "Config:"
	@echo "  make config           edit config.toml + secrets.toml"
	@echo "  make email-auth       (re)authenticate Outlook IMAP (device-code login)"
	@echo ""
	@echo "Schedule (systemd user timer):"
	@echo "  make timers-install   install + enable the daily fetch timer"
	@echo "  make timers-status    show timer state"
	@echo "  make timers-logs      tail the fetch service logs"
	@echo "  make timers-uninstall disable + remove the timer"
	@echo ""
	@echo "Utilities:"
	@echo "  make mcp-setup        register the MCP server with Claude Code"
	@echo "  make show-digest      print the latest digest"
	@echo ""
	@echo "Dev:"
	@echo "  make dev              install dev+runtime deps + git hooks"
	@echo "  make test  lint  fmt  typecheck  check  clean  distclean"
	@echo ""
	@echo "Paths:  data=~/.local/share/karyab  config=$${XDG_CONFIG_HOME:-~/.config}/karyab"

# --- venv / install -------------------------------------------------------

$(PY):
	$(PYTHON) -m venv $(VENV)
	$(PIP) install -q --upgrade pip

.PHONY: install
install: $(PY)
	$(PIP) install -q -e ".[rank,mcp,oauth]"
	@echo "installed karyab into $(VENV)"

.PHONY: dev
dev: $(PY)
	$(PIP) install -q -e ".[dev,rank,mcp,oauth]"
	$(BIN)/pre-commit install
	@echo "dev environment ready"

# --- setup / config -------------------------------------------------------

.PHONY: init
init: install
	$(KARYAB) init

# One-shot bootstrap: deps, dirs+db, and private config+secrets from examples.
# Interactive TTY: guided prompts for config editing, email auth, first fetch.
.PHONY: setup
setup: init
	@cfg="$(CONFIG_DIR)"; \
	[ -f "$$cfg/config.toml" ]  || { cp config.example.toml  "$$cfg/config.toml"; echo "created $$cfg/config.toml"; }; \
	if [ ! -f "$$cfg/secrets.toml" ]; then \
		cp secrets.example.toml "$$cfg/secrets.toml"; chmod 600 "$$cfg/secrets.toml"; \
		echo "created $$cfg/secrets.toml (chmod 600)"; \
	fi; \
	if [ -t 0 ]; then \
		printf 'Edit your config + secrets now? [Y/n] '; read ans; \
		case "$$ans" in \
			[nN]) ;; \
			*) \
				echo "editing $$cfg/config.toml"; \
				$(EDITOR) "$$cfg/config.toml"; \
				echo "editing $$cfg/secrets.toml (keys, app-passwords)"; \
				$(EDITOR) "$$cfg/secrets.toml" ;; \
		esac; \
		printf 'Authenticate Outlook email now? (skip if not using email alerts) [y/N] '; read ans; \
		case "$$ans" in \
			[yY]) $(KARYAB) email-auth ;; \
		esac; \
		printf 'Run a first fetch now? (can take a while) [y/N] '; read ans; \
		case "$$ans" in \
			[yY]) $(KARYAB) fetch ;; \
		esac; \
	fi; \
	echo ""; \
	echo "Done. Try:  make start   (web UI)   or   make run   (pipeline)"

# Edit your private config + secrets (creates them from examples if missing).
.PHONY: config
config: install
	@cfg="$(CONFIG_DIR)"; mkdir -p "$$cfg"; \
	[ -f "$$cfg/config.toml" ]  || cp config.example.toml  "$$cfg/config.toml"; \
	if [ ! -f "$$cfg/secrets.toml" ]; then cp secrets.example.toml "$$cfg/secrets.toml"; chmod 600 "$$cfg/secrets.toml"; fi; \
	echo "editing $$cfg/config.toml"; \
	$(EDITOR) "$$cfg/config.toml"; \
	echo "editing $$cfg/secrets.toml (keys, app-passwords)"; \
	$(EDITOR) "$$cfg/secrets.toml"

# --- email auth -----------------------------------------------------------

.PHONY: email-auth
email-auth: install
	$(KARYAB) email-auth

# --- run ------------------------------------------------------------------

.PHONY: run
run: install
	$(KARYAB) fetch
	$(KARYAB) rank
	$(KARYAB) digest

.PHONY: fetch
fetch: install
	$(KARYAB) fetch

.PHONY: rank
rank: install
	$(KARYAB) rank

.PHONY: digest
digest: install
	$(KARYAB) digest

.PHONY: followups
followups: install
	$(KARYAB) followups

.PHONY: apply
apply: install
	@test -n "$(JOB)" || { echo "usage: make apply JOB=<job-id>"; exit 2; }
	$(KARYAB) apply "$(JOB)"

.PHONY: mcp
mcp: install
	$(BIN)/karyab-mcp

.PHONY: mcp-setup
mcp-setup: install
	$(KARYAB) mcp-setup

.PHONY: show-digest
show-digest: install
	@d="$$($(PY) -c 'import karyab.config as c; print(c.digests_dir())')/digest-latest.md"; \
	[ -f "$$d" ] && cat "$$d" || echo "no digest yet — run 'make digest'"

# --- systemd user timer ---------------------------------------------------

.PHONY: timers-install
timers-install:
	@command -v systemctl >/dev/null || { echo "systemctl not found — manual scheduling only"; exit 1; }
	mkdir -p $(SYSTEMD_USER_DIR)
	install -m 0644 systemd/karyab-fetch.service $(SYSTEMD_USER_DIR)/
	install -m 0644 systemd/karyab-fetch.timer   $(SYSTEMD_USER_DIR)/
	@echo "NOTE: units call %h/.local/bin/karyab — if karyab lives in .venv,"
	@echo "      either 'pipx install .' or edit ExecStart to $(CURDIR)/$(KARYAB)."
	systemctl --user daemon-reload
	systemctl --user enable --now karyab-fetch.timer
	systemctl --user list-timers karyab-fetch.timer --no-pager

.PHONY: timers-status
timers-status:
	systemctl --user list-timers karyab-fetch.timer --no-pager || true
	systemctl --user status karyab-fetch.timer --no-pager || true

.PHONY: timers-logs
timers-logs:
	journalctl --user -u karyab-fetch.service -n 50 --no-pager

.PHONY: timers-uninstall
timers-uninstall:
	-systemctl --user disable --now karyab-fetch.timer
	-rm -f $(SYSTEMD_USER_DIR)/karyab-fetch.service $(SYSTEMD_USER_DIR)/karyab-fetch.timer
	-systemctl --user daemon-reload
	@echo "timer removed"

# --- dev quality ----------------------------------------------------------

.PHONY: test
test: dev
	$(BIN)/pytest

.PHONY: lint
lint: dev
	$(BIN)/ruff check .

.PHONY: fmt
fmt: dev
	$(BIN)/ruff format .

.PHONY: typecheck
typecheck: dev
	$(BIN)/mypy src

.PHONY: check
check: dev
	$(BIN)/pre-commit run --all-files

.PHONY: clean
clean:
	rm -rf build dist *.egg-info .pytest_cache .ruff_cache .mypy_cache
	find . -type d -name __pycache__ -prune -exec rm -rf {} +

.PHONY: distclean
distclean: clean
	rm -rf $(VENV)

# --- web UI (container) -------------------------------------------------------
# UI port (same inside container and on host). Default 16666 — NOT 6665-6669,
# which browsers block as unsafe (old IRC ports → ERR_UNSAFE_PORT, request never
# sent). Published on 127.0.0.1 only: nothing listens on IPv6 ::1, so a browser
# resolving localhost→::1 fast-fails and falls back to 127.0.0.1 (rootless podman
# can't serve IPv6 loopback). Override: make start UI_PORT=8666
UI_PORT ?= 16666

.PHONY: start-build
start-build:
	$(CONTAINER) build -t karyab-ui .

.PHONY: start
start: start-build
	$(CONTAINER) run --rm -d --name karyab-ui -p 127.0.0.1:$(UI_PORT):$(UI_PORT) \
		-e XDG_DATA_HOME=/data \
		-e XDG_CONFIG_HOME=/config \
		-v $$HOME/.local/share/karyab:/data/karyab \
		-v $$HOME/.config/karyab:/config/karyab:ro \
		karyab-ui
	@echo "karyab UI → http://localhost:$(UI_PORT)  (or http://127.0.0.1:$(UI_PORT))"

.PHONY: stop
stop:
	-$(CONTAINER) stop karyab-ui

.PHONY: logs
logs:
	$(CONTAINER) logs -f karyab-ui
