#!/usr/bin/env bash
# software.muki.tw — 本機 Mac 常用軟體掃描工具
# 完全在你的 Mac 本機執行，不上傳任何資料。
# 產出：~/Desktop/my-mac-2026.json（含真實 App Icon）並開啟 software.muki.tw 帶入清單。

set -euo pipefail

SITE_URL="${SOFTWARE_MUKI_URL:-https://software.muki.tw}"
OUT_JSON="$HOME/Desktop/my-mac-2026.json"

echo "🔍 正在掃描你的 Mac 已安裝軟體與近一年的 Spotlight 使用紀錄..."

python3 - "$SITE_URL" "$OUT_JSON" <<'PYEOF'
import os, re, sys, glob, json, base64, shutil, plistlib, subprocess, tempfile
from datetime import datetime, timedelta, timezone
from concurrent.futures import ThreadPoolExecutor

site_url = sys.argv[1].rstrip("/")
out_json = sys.argv[2]

# Active days are counted over the 365 calendar days ending today (local time)
WINDOW_DAYS = 365
today = datetime.now().astimezone().date()
since = today - timedelta(days=WINDOW_DAYS - 1)

ROOTS = ["/Applications", os.path.expanduser("~/Applications"), "/System/Applications"]
MAX_DEPTH = 8
TERMINAL_APP = "/System/Applications/Utilities/Terminal.app"

def find_apps(root):
    found = []
    if not os.path.isdir(root):
        return found
    base_depth = root.rstrip("/").count("/")
    for dirpath, dirnames, _ in os.walk(root):
        keep = []
        for d in dirnames:
            if d.startswith("."):
                continue
            full = os.path.join(dirpath, d)
            if d.endswith(".app"):
                found.append(full)
            elif not os.path.islink(full) and full.count("/") - base_depth < MAX_DEPTH:
                keep.append(d)
        dirnames[:] = keep
    return found

app_paths = sorted({p for root in ROOTS for p in find_apps(root)})

# Collect local author tokens (macOS username + git user.name) to detect self-built apps
author_tokens = set()
for tok in [os.environ.get("USER", ""), os.path.basename(os.path.expanduser("~"))]:
    tok = tok.strip().lower()
    if len(tok) >= 3:
        author_tokens.add(tok)
try:
    git_name = subprocess.check_output(["git", "config", "--global", "user.name"], text=True, stderr=subprocess.DEVNULL).strip().lower()
    for part in git_name.replace("-", " ").replace("_", " ").split():
        if len(part) >= 3:
            author_tokens.add(part)
    git_email = subprocess.check_output(["git", "config", "--global", "user.email"], text=True, stderr=subprocess.DEVNULL).strip().lower()
    if "@" in git_email:
        local_part, domain = git_email.split("@", 1)
        if len(local_part) >= 3:
            author_tokens.add(local_part)
        domain_root = domain.split(".")[0]
        if domain_root not in ("gmail", "icloud", "outlook", "hotmail", "yahoo", "me", "qq", "163", "proton", "protonmail") and len(domain_root) >= 3:
            author_tokens.add(domain_root)
except Exception:
    pass

def signing_info(path):
    # Returns the code-signing team id and the lowercased Authority lines
    try:
        cs = subprocess.run(["codesign", "-dvv", path], capture_output=True, text=True, timeout=2)
    except Exception:
        return "", []
    lines = (cs.stderr or "").splitlines()
    team = next((l.split("=", 1)[1].strip() for l in lines if l.startswith("TeamIdentifier=")), "")
    authorities = [l.lower() for l in lines if l.startswith("Authority=")]
    return ("" if team == "not set" else team), authorities

def matches_author(bid, authorities):
    bid_low = bid.lower()
    if bid_low and any(tok in bid_low for tok in author_tokens):
        return True
    return any(tok in line for line in authorities for tok in author_tokens)

MEDIA_KEYWORDS = ["cleanshot", "screenstudio", "focusee", "gifox", "filmage", "hyperframes", "quicktime", "podcast",
                  "music", "spotify", "iina", "vlc", "infuse", "obsproject", "capcut", "davinci", "finalcut", "imovie",
                  "garageband", "com.apple.logic", "photos", "pixelmator", "affinity", "figma", "sketch", "photoshop",
                  "lightroom", "illustrator", "premiere", "blender", "mockuuups", "hongguo", "huangguo", "短劇", "短剧", "影視", "影视"]
MEDIA_LS_TYPES = {"public.app-category.entertainment", "public.app-category.video", "public.app-category.photography",
                  "public.app-category.music", "public.app-category.graphics-design"}

def guess_category(name: str, bid: str, path: str, ls_type: str) -> str:
    name_low = name.lower()
    # The bundle file name stays English when the display name is localized (備忘錄 → Notes)
    s = f"{name} {os.path.basename(path)} {bid}".lower()
    if name_low in ("dia", "arc", "line") or any(k in s for k in ["thebrowser.dia", "thebrowser.browser", "chrome", "safari", "firefox", "brave", "edge", "slack", "discord", "teams", "telegram", "wechat", "whatsapp", "zoom", "tailscale", "mail", "spark", "mimestream", "clash", "vpn"]):
        return "browse-comm"
    if any(k in s for k in ["claude", "chatgpt", "openai", "cursor", "vscode", "code", "xcode", "zed", "ghostty", "iterm", "warp", "term", "ollama", "lmstudio", "docker", "orbstack", "navicat", "tableplus", "postman", "github", "sublime", "jetbrains", "webstorm", "perplexity", "grok", "herdr", "orbit", "antigravity", "windsurf"]):
        return "ai-dev"
    if any(k in s for k in ["obsidian", "notion", "hyread", "eagle", "notes", "craft", "bear", "ulysses", "typora", "heptabase", "logseq", "reeder", "readwise", "kindle", "books", "word", "excel", "powerpoint", "pages", "keynote", "numbers", "goodnotes", "things", "ticktick", "todoist", "preview", "textedit", "wpsoffice", "poedit"]):
        return "read-write"
    if any(k in s for k in MEDIA_KEYWORDS) or ls_type in MEDIA_LS_TYPES or ls_type.endswith("games"):
        return "media-create"
    return "prod-create"

# Dock pinned apps & running GUI apps, matched by bundle id so localized names do not matter
dock_ids = set()
try:
    dock_out = subprocess.check_output(["defaults", "read", "com.apple.dock", "persistent-apps"], text=True, stderr=subprocess.DEVNULL)
    for m in re.finditer(r'"bundle-identifier"\s*=\s*"([^"]+)"', dock_out):
        dock_ids.add(m.group(1).lower())
except Exception:
    pass

running_ids = set()
try:
    run_out = subprocess.check_output(
        ["osascript", "-e", 'tell application "System Events" to get bundle identifier of every application process whose background only is false'],
        text=True, stderr=subprocess.DEVNULL
    )
    for item in run_out.split(","):
        s = item.strip().lower()
        if s and s != "missing value":
            running_ids.add(s)
except Exception:
    pass

DATE_RE = r"\d{4}-\d\d-\d\d \d\d:\d\d:\d\d [+-]\d{4}"

def local_day(value: str):
    return datetime.strptime(value, "%Y-%m-%d %H:%M:%S %z").astimezone().date()

def read_bundle_info(path, meta):
    # iPhone and iPad apps installed on Apple silicon keep their Info.plist under WrappedBundle
    for rel in (("Contents", "Info.plist"), ("WrappedBundle", "Info.plist")):
        try:
            with open(os.path.join(path, *rel), "rb") as f:
                pl = plistlib.load(f)
            bid = str(pl.get("CFBundleIdentifier", "")).strip()
            if bid:
                return bid, str(pl.get("LSApplicationCategoryType", "")).strip()
        except Exception:
            pass
    m = re.search(r'^kMDItemCFBundleIdentifier\s*=\s*"(.+)"$', meta, re.M)
    return (m.group(1).strip() if m else ""), ""

def read_app(path):
    try:
        meta = subprocess.run(
            ["mdls", "-name", "kMDItemCFBundleIdentifier", "-name", "kMDItemUseCount", "-name", "kMDItemLastUsedDate",
             "-name", "kMDItemUsedDates", "-name", "kMDItemDisplayName", path],
            capture_output=True, text=True, timeout=5
        ).stdout
    except Exception:
        meta = ""
    bid, ls_type = read_bundle_info(path, meta)
    if not bid:
        return None
    m = re.search(r'^kMDItemDisplayName\s*=\s*"(.+)"$', meta, re.M)
    # Spotlight's display name follows the system language (Notes → 備忘錄)
    name = re.sub(r"\.app$", "", m.group(1)).strip() if m else ""
    name = name or os.path.basename(path)[:-4]
    m = re.search(r"^kMDItemUseCount\s*=\s*(\d+)", meta, re.M)
    count = int(m.group(1)) if m else 0
    m = re.search(rf"^kMDItemLastUsedDate\s*=\s*({DATE_RE})", meta, re.M)
    last_used = datetime.strptime(m.group(1), "%Y-%m-%d %H:%M:%S %z") if m else None
    if last_used and not since <= last_used.astimezone().date() <= today:
        last_used = None
    m = re.search(r"^kMDItemUsedDates\s*=\s*\(([^)]*)\)", meta, re.M)
    days = {local_day(d) for d in re.findall(DATE_RE, m.group(1))} if m else set()
    in_window = sorted(d for d in days if since <= d <= today)
    active_days = len(in_window)
    return {
        "name": name,
        "bundleId": bid,
        "path": path,
        "count": count,
        "activeDays": active_days,
        "firstDay": in_window[0].isoformat() if in_window else "",
        # Full UTC timestamp so apps last used on the same day still sort by time
        "lastUsed": last_used.astimezone(timezone.utc).isoformat() if last_used else "",
        "inDock": bid.lower() in dock_ids,
        "isRunning": bid.lower() in running_ids,
        "lsType": ls_type,
    }

with ThreadPoolExecutor(max_workers=8) as pool:
    scanned = [a for a in pool.map(read_app, app_paths) if a]

def rank(a):
    return (a["activeDays"], a["count"], a["lastUsed"], a["isRunning"], a["inDock"])

# The same bundle id can be installed twice (for example traditional and simplified Chinese builds)
unique = {}
for a in scanned:
    key = a["bundleId"].lower()
    if key not in unique or rank(a) > rank(unique[key]):
        unique[key] = a
installed = list(unique.values())
path_by_id = {a["bundleId"].lower(): a["path"] for a in installed}

rows = []
for a in installed:
    if a["activeDays"] or a["lastUsed"] or a["inDock"] or a["isRunning"]:
        rows.append(a)

# Command-line AI tools have no app bundle, so Spotlight has no usage record for them
CLI_TOOLS = [
    ("claude", "Claude Code", "cli:claude-code", ["com.anthropic.claudefordesktop"]),
    ("codex", "Codex CLI", "cli:codex", ["com.openai.codex", "com.openai.chat"]),
    ("gemini", "Gemini CLI", "cli:gemini", []),
]
home = os.path.expanduser("~")
extra_bins = [os.path.join(home, p) for p in (".local/bin", ".claude/local", ".bun/bin", ".npm-global/bin")]
extra_bins += ["/opt/homebrew/bin", "/usr/local/bin"] + sorted(glob.glob(os.path.join(home, ".nvm/versions/node/*/bin")))
search_path = os.pathsep.join([os.environ.get("PATH", "")] + extra_bins)
for cmd, label, cli_id, icon_ids in CLI_TOOLS:
    if not shutil.which(cmd, path=search_path):
        continue
    icon_path = next((path_by_id[i] for i in icon_ids if i in path_by_id), TERMINAL_APP)
    rows.append({"name": label, "bundleId": cli_id, "path": icon_path, "count": 0, "activeDays": 0, "firstDay": "",
                 "lastUsed": "", "inDock": False, "isRunning": False, "category": "ai-dev"})

# Self-built apps are matched by author tokens, then by sharing a signing team with one of them
with ThreadPoolExecutor(max_workers=8) as pool:
    signs = list(pool.map(lambda a: ("", []) if a.get("category") else signing_info(a["path"]), rows))
self_built = [not a.get("category") and matches_author(a["bundleId"], auths) for a, (_, auths) in zip(rows, signs)]
custom_teams = {team for (team, _), own in zip(signs, self_built) if own and team}
for a, (team, _), own in zip(rows, signs, self_built):
    if a.get("category"):
        continue
    if own or (team and team in custom_teams):
        a["category"] = "custom"
    else:
        a["category"] = guess_category(a["name"], a["bundleId"], a["path"], a.get("lsType", ""))

rows.sort(key=rank, reverse=True)

cat_defs = [
    ("custom", "個人作品"),
    ("ai-dev", "AI 與開發"),
    ("browse-comm", "網路與通訊"),
    ("read-write", "閱讀與筆記"),
    ("media-create", "影音與創作"),
    ("prod-create", "系統工具"),
]

# Every app with recent usage is kept; people remove what they do not want on the web page
selected_by_cat = {cid: [a for a in rows if a["category"] == cid] for cid, _ in cat_defs}
top_apps = [a for cid, _ in cat_defs for a in selected_by_cat[cid]]

# Extract 128x128 PNG icons via Swift NSWorkspace
icon_map = {}
if top_apps:
    with tempfile.TemporaryDirectory() as tmpdir:
        paths_file = os.path.join(tmpdir, "paths.json")
        with open(paths_file, "w", encoding="utf-8") as f:
            json.dump([a["path"] for a in top_apps], f)

        swift_code = r'''
import AppKit
import Foundation

let args = CommandLine.arguments
let pathsData = try Data(contentsOf: URL(fileURLWithPath: args[1]))
let paths = try JSONDecoder().decode([String].self, from: pathsData)
let outDir = args[2]
let size = NSSize(width: 128, height: 128)

for (idx, p) in paths.enumerated() {
    let resolved = URL(fileURLWithPath: p).resolvingSymlinksInPath().path
    let icon = NSWorkspace.shared.icon(forFile: resolved)
    let rep = NSBitmapImageRep(
        bitmapDataPlanes: nil, pixelsWide: 128, pixelsHigh: 128,
        bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
        colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0
    )!
    rep.size = size
    NSGraphicsContext.saveGraphicsState()
    NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
    NSGraphicsContext.current?.imageInterpolation = .high
    icon.draw(in: NSRect(origin: .zero, size: size), from: .zero, operation: .copy, fraction: 1.0)
    NSGraphicsContext.restoreGraphicsState()
    if let png = rep.representation(using: .png, properties: [:]) {
        try? png.write(to: URL(fileURLWithPath: "\(outDir)/\(idx).png"))
    }
}
'''
        try:
            subprocess.run(["swift", "-", paths_file, tmpdir], input=swift_code, text=True, check=True, stderr=subprocess.DEVNULL)
            for idx, a in enumerate(top_apps):
                png_path = os.path.join(tmpdir, f"{idx}.png")
                if os.path.exists(png_path):
                    with open(png_path, "rb") as f:
                        icon_map[idx] = "data:image/png;base64," + base64.b64encode(f.read()).decode("ascii")
        except Exception:
            pass

icon_index = {id(a): i for i, a in enumerate(top_apps)}
grouped_full = []
grouped_url = []

for cid, clabel in cat_defs:
    cat_apps = selected_by_cat.get(cid, [])
    if not cat_apps:
        continue
    full_list = []
    url_list = []
    for a in cat_apps:
        cnt_str = f"{a['count']:,}" if a["count"] > 0 else ("Dock" if a.get("inDock") else "")
        entry = {"name": a["name"], "bundleId": a["bundleId"], "count": cnt_str}
        url_list.append(entry)
        full_list.append({**entry, "icon": icon_map.get(icon_index[id(a)], "")})
    grouped_full.append({"id": cid, "label": clabel, "apps": full_list})
    grouped_url.append({"id": cid, "label": clabel, "apps": url_list})

title = "2026 我的 Mac 常用軟體"
with open(out_json, "w", encoding="utf-8") as f:
    json.dump({"title": title, "categories": grouped_full}, f, ensure_ascii=False, indent=2)

raw_bytes = json.dumps({"title": title, "categories": grouped_url}, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
encoded = base64.urlsafe_b64encode(raw_bytes).decode("ascii").rstrip("=")
# The fragment stays in the browser, so the app list never reaches the server or analytics
import_url = f"{site_url}/#import={encoded}"

if any(a["activeDays"] for a in rows):
    earliest = min(a["firstDay"] for a in rows if a["firstDay"])
    # Spotlight may keep a shorter history than the requested window, so report what it actually covers
    source = f"近一年活躍天數（{since.isoformat()} 至 {today.isoformat()}，Spotlight 最早紀錄為 {earliest}）"
elif any(a["lastUsed"] for a in rows):
    source = "最後使用時間（Spotlight 未提供活躍天數）"
else:
    source = "Dock 固定項目與執行中的 App（Spotlight 未提供使用紀錄）"

print(f"\n✅ 掃描完成！共列出 {len(top_apps)} 款軟體，排序依據：{source}")
for cid, clabel in cat_defs:
    apps = selected_by_cat[cid]
    if apps:
        print(f"   {clabel}：{len(apps)} 款")
if not any(a["activeDays"] or a["lastUsed"] for a in rows):
    print("⚠️ 無法讀取 Spotlight 使用紀錄，本次僅依 Dock 固定項目與執行中的 App 列出。")
    print("   若於 AI 工具的沙箱內執行，請改於「終端機」執行本指令；亦可執行 mdutil -s / 確認 Spotlight 索引已啟用。")
print(f"📁 完整資料（含本機真實 Icon）已存至：{out_json}")
print(f"🌐 正在為你開啟網頁：{site_url}")
print("\n💡 請把桌面的 my-mac-2026.json 拖進網頁以載入全部真實 Icon；每列超過 8 款時，請在網頁上刪除不需要的軟體，再匯出或發布海報。")

subprocess.run(["open", import_url], check=False)
PYEOF
