#!/usr/bin/env python3
"""CCC - what is everything in ~/Code?

From "Four agents, one window" - https://intlo.com/news/four-agents-one-window
No dependencies beyond python3. Set CCC_ROOT to point it at another folder.

Lists every project folder with a one-line summary of what it is, its stack,
and its git state. Summaries come from (in order): your own override file,
package.json "description", the first prose line of README, then CLAUDE.md
or AGENTS.md.

  CCC                 everything, newest commit first
  CCC <text>          only projects matching <text> (name or summary), full detail
  CCC -a              alphabetical
  CCC -d              only repos with uncommitted changes
  CCC -s              only stale repos (no commit in 60 days)
  CCC -l              long form: full summaries, no truncation
  CCC -w <proj> <txt> write/replace your own summary for <proj>
  CCC -r              re-scan now (results are cached for 15 min)
  CCC -h              this help
"""
import json
import os
import re
import subprocess
import unicodedata
import sys
import time
from concurrent.futures import ThreadPoolExecutor

ROOT = os.path.expanduser(os.environ.get("CCC_ROOT", "~/Code"))
STORE = os.path.join(ROOT, ".ccc")
OVERRIDES = os.path.join(STORE, "summaries.tsv")
STALE_DAYS = 60
SKIP = {"node_modules"}

CACHED = [False]
TTY = sys.stdout.isatty() and not os.environ.get("NO_COLOR")


def safe_text(value):
    """Neutralize terminal controls in repository-owned display strings."""
    return "".join(ch for ch in str(value) if not unicodedata.category(ch).startswith("C"))


def c(code, s):
    return "\033[%sm%s\033[0m" % (code, s) if TTY else str(s)


TEAL = "38;5;37"
GREEN = "38;5;71"
AMBER = "38;5;208"
RED = "38;5;167"
DIM = "38;5;243"
BOLD = "1"


def term_width():
    try:
        import shutil
        return max(80, min(shutil.get_terminal_size((120, 40)).columns, 200))
    except Exception:
        return 120


# ---------------------------------------------------------------- summaries

def clean(text):
    t = text.strip()
    t = re.sub(r"!\[[^\]]*\]\([^)]*\)", "", t)          # images
    t = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", t)       # links -> text
    t = re.sub(r"<[^>]+>", "", t)                        # html
    t = t.replace("**", "").replace("`", "").replace("*", "")
    t = re.sub(r"\s+", " ", t)
    return t.strip(" .,:;-")


BOILERPLATE = (
    "bootstrapped with create-next-app",
    "this version has breaking changes",
    "getting started",
    "first, run the development server",
    "run the development server",
    "open http://localhost",
    "to learn more about",
    "check out our",
    "deploy on vercel",
    "routine updates may be committed",
    "this repository belongs to",
    "npm install",
    "pnpm install",
    "yarn install",
    "clone the repo",
    "see the documentation",
    "all rights reserved",
    "licensed under",
    "work in progress",
    "coming soon",
    "you can start editing the page",
    "this block is written and re-added by next dev",
    "boilerplate and starter for next.js",
    "vercel auto-deploys",
    "this repo is worked on by multiple ai sessions",
    "the root for everything in this product",
    "auto-updates as you edit",
    "save and see your changes",
    "this project uses",
    "next.js github repository",
    "clone this project and use it",
    "your feedback and contributions",
    "check out the live",
    "deploy your next.js app",
    "is the easiest way to deploy",
)


def is_junk(s):
    low = s.lower()
    if any(b in low for b in BOILERPLATE):
        return True
    if '="' in s or s.startswith("src=") or s.endswith("/>"):
        return True
    if re.match(r"^(v?\d+\.\d|version\b|status\b|last updated\b|owner\b|branch\b)", low):
        return True
    if len(s.split()) < 4:
        return True
    if s.count("|") >= 3:
        return True
    # instruction/rule lines from CLAUDE.md-style files are not descriptions
    if re.search(r"\b(must|must not|should|shouldn't|do not|don't|never|always|assume|verify)\b", low):
        return True
    if re.match(r"^(spec|status|owner|note|warning|important|todo|next)\s*:", low):
        return True
    if s[:1].islower():          # mid-sentence fragment
        return True
    return False


def first_prose(path, limit=80):
    try:
        with open(path, "r", errors="replace") as fh:
            lines = [next(fh, "") for _ in range(limit)]
    except Exception:
        return ""
    in_fence = False
    for raw in lines:
        s = raw.strip()
        if s.startswith("```"):
            in_fence = not in_fence
            continue
        if in_fence or not s:
            continue
        if s.startswith(("#", ">", "|", "-", "*", "+", "<", "!", "[", "=", "---")):
            continue
        if re.match(r"^\d+[.)]\s", s):
            continue
        out = clean(s)
        if len(out) > 25 and not is_junk(out):
            return out
    return ""


def pkg_info(d):
    p = os.path.join(d, "package.json")
    if not os.path.isfile(p):
        return None
    try:
        with open(p, "r", errors="replace") as fh:
            return json.load(fh)
    except Exception:
        return {}


def detect_stack(d, pkg):
    if pkg:
        deps = {}
        for k in ("dependencies", "devDependencies"):
            deps.update(pkg.get(k) or {})
        for key, label in (
            ("next", "next"), ("@remix-run/react", "remix"), ("astro", "astro"),
            ("nuxt", "nuxt"), ("payload", "payload"), ("expo", "expo"),
            ("react-native", "rn"), ("electron", "electron"), ("vite", "vite"),
            ("svelte", "svelte"), ("express", "express"), ("fastify", "fastify"),
            ("react", "react"), ("vue", "vue"),
        ):
            if key in deps:
                return label
        return "node"
    for f, label in (
        ("pyproject.toml", "python"), ("requirements.txt", "python"),
        ("Cargo.toml", "rust"), ("go.mod", "go"), ("Package.swift", "swift"),
        ("Gemfile", "ruby"), ("composer.json", "php"), ("docker-compose.yml", "docker"),
    ):
        if os.path.isfile(os.path.join(d, f)):
            return label
    try:
        names = os.listdir(d)
    except Exception:
        names = []
    if any(n.endswith(".xcodeproj") for n in names):
        return "swift"
    if any(n.endswith((".php",)) for n in names):
        return "php"
    if "index.html" in names:
        return "static"
    if any(n.endswith(".json") for n in names) and not names:
        return ""
    return ""


def readme_path(d):
    try:
        for n in sorted(os.listdir(d)):
            if n.lower().startswith("readme"):
                return os.path.join(d, n)
    except Exception:
        pass
    return None


def load_overrides():
    out = {}
    if os.path.isfile(OVERRIDES):
        with open(OVERRIDES, "r", errors="replace") as fh:
            for line in fh:
                if "\t" in line and not line.startswith("#"):
                    k, v = line.rstrip("\n").split("\t", 1)
                    out[k] = v.strip()
                    out[k.strip()] = v.strip()
    return out


def summarize(d, pkg, overrides):
    name = os.path.basename(d)
    if name in overrides:
        return overrides[name], "you"
    if name.strip() in overrides:
        return overrides[name.strip()], "you"
    if pkg:
        desc = (pkg.get("description") or "").strip()
        if len(desc) > 10:
            return clean(desc), "pkg"
    r = readme_path(d)
    if r:
        s = first_prose(r)
        if s:
            return s, "readme"
    for f, tag in (("CLAUDE.md", "claude"), ("AGENTS.md", "agents"), ("PROGRESS.md", "progress")):
        p = os.path.join(d, f)
        if os.path.isfile(p):
            s = first_prose(p)
            if s:
                return s, tag
    return "", ""


# ---------------------------------------------------------------------- git

def git(d, *args):
    try:
        r = subprocess.run(
            ["git", "-C", d, "--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null"] + list(args),
            capture_output=True, text=True, timeout=20,
        )
        return r.stdout.strip() if r.returncode == 0 else ""
    except Exception:
        return ""


def git_state(d):
    if not os.path.isdir(os.path.join(d, ".git")):
        return {"repo": False}
    branch = git(d, "rev-parse", "--abbrev-ref", "HEAD") or "-"
    ts = git(d, "log", "-1", "--format=%ct")
    porcelain = git(d, "status", "--porcelain")
    remote = git(d, "config", "--get", "remote.origin.url")
    return {
        "repo": True,
        "branch": branch,
        "ts": int(ts) if ts.isdigit() else 0,
        "dirty": len([x for x in porcelain.splitlines() if x.strip()]),
        "remote": remote,
    }


def age(ts, now):
    if not ts:
        return "-"
    s = now - ts
    if s < 3600:
        return "%dm" % max(1, s // 60)
    if s < 86400:
        return "%dh" % (s // 3600)
    if s < 86400 * 14:
        return "%dd" % (s // 86400)
    if s < 86400 * 60:
        return "%dw" % (s // (86400 * 7))
    if s < 86400 * 730:
        return "%dmo" % (s // (86400 * 30))
    return "%dy" % (s // (86400 * 365))


# -------------------------------------------------------------------- scan

def scan():
    overrides = load_overrides()
    try:
        entries = sorted(
            n for n in os.listdir(ROOT)
            if not n.startswith(".") and n not in SKIP
            and os.path.isdir(os.path.join(ROOT, n))
        )
    except FileNotFoundError:
        sys.exit("CCC: no such folder: %s" % ROOT)

    def build(name):
        d = os.path.join(ROOT, name)
        pkg = pkg_info(d)
        summary, src = summarize(d, pkg, overrides)
        g = git_state(d)
        return {
            "name": name, "dir": d, "stack": detect_stack(d, pkg),
            "summary": summary, "src": src, **g,
        }

    with ThreadPoolExecutor(max_workers=16) as ex:
        projects = list(ex.map(build, entries))

    seen = {}
    for p in projects:
        r = (p.get("remote") or "").rstrip("/").replace(".git", "").lower()
        if r:
            seen.setdefault(r, []).append(p["name"])
    for p in projects:
        r = (p.get("remote") or "").rstrip("/").replace(".git", "").lower()
        p["dup"] = len(seen.get(r, [])) > 1
    return projects


CACHE = os.path.join(STORE, "cache.json")
CACHE_TTL = 900


def scan_cached(refresh=False):
    if not refresh and os.path.isfile(CACHE):
        try:
            with open(CACHE) as fh:
                blob = json.load(fh)
            if time.time() - blob.get("at", 0) < CACHE_TTL:
                return blob["projects"], True
        except Exception:
            pass
    projects = scan()
    try:
        os.makedirs(STORE, exist_ok=True)
        tmp = CACHE + ".tmp"
        with open(tmp, "w") as fh:
            json.dump({"at": time.time(), "projects": projects}, fh)
        os.replace(tmp, CACHE)
    except Exception:
        pass
    return projects, False


# ------------------------------------------------------------------ render

def trunc(s, n):
    if n <= 1:
        return ""
    return s if len(s) <= n else s[: n - 1].rstrip() + "…"


def git_cell(p, now):
    if not p.get("repo"):
        return c(DIM, "no git"), 6
    br = p["branch"]
    br = br if len(br) <= 14 else br[:13] + "…"
    mark = " ✱" if p.get("dirty") else "  "
    plain = "%s%s %s" % (br, mark, age(p["ts"], now))
    col = AMBER if p.get("dirty") else GREEN
    return c(col, br) + c(AMBER, mark) + " " + c(DIM, age(p["ts"], now)), len(plain)


def render(projects, long=False, detail=False):
    projects = [{k: safe_text(v) if isinstance(v, str) else v for k, v in p.items()} for p in projects]
    now = int(time.time())
    w = term_width()
    namew = min(max([len(p["name"]) for p in projects] + [10]), 32)

    head = "  %s  %s" % (c(BOLD + ";" + TEAL, "CODE"),
                         c(DIM, "%s · %d projects" % (safe_text(ROOT.replace(os.path.expanduser("~"), "~")), len(projects))))
    print()
    print(head)
    print()

    if detail or long:
        for p in projects:
            gc, _ = git_cell(p, now)
            bits = [c(BOLD, p["name"])]
            if p["stack"]:
                bits.append(c(TEAL, p["stack"]))
            bits.append(gc)
            if p.get("dup"):
                bits.append(c(RED, "shares its remote with another folder"))
            print("  " + c(DIM, " · ").join(bits))
            s = p["summary"] or c(DIM, "no description found - add one with: CCC -w \"%s\" \"...\"" % p["name"])
            for line in wrap(s, w - 6):
                print("    " + line)
            if p.get("remote"):
                print("    " + c(DIM, p["remote"]))
            print()
        return

    sumw = w - (namew + 12 + 22 + 6)
    for p in projects:
        gc, glen = git_cell(p, now)
        stack = p["stack"] or "-"
        line = "  %s  %s  %s%s  %s" % (
            c(BOLD, p["name"].ljust(namew)[:namew]),
            c(TEAL, stack.ljust(9)[:9]),
            gc, " " * max(0, 22 - glen),
            (c(RED, "dup ") if p.get("dup") else "") + (trunc(p["summary"], sumw - (4 if p.get("dup") else 0)) if p["summary"] else c(DIM, "no description")),
        )
        print(line)
    print()
    dirty = sum(1 for p in projects if p.get("dirty"))
    nodesc = sum(1 for p in projects if not p["summary"])
    stale = sum(1 for p in projects if p.get("repo") and p["ts"] and (now - p["ts"]) > STALE_DAYS * 86400)
    dups = sum(1 for p in projects if p.get("dup"))
    print("  " + c(DIM, "%d uncommitted · %d stale (>%dd) · %d without a description"
                  % (dirty, stale, STALE_DAYS, nodesc)))
    print()


def wrap(s, width):
    words, line, out = s.split(), "", []
    for wd in words:
        if len(line) + len(wd) + 1 > width:
            out.append(line)
            line = wd
        else:
            line = (line + " " + wd).strip()
    if line:
        out.append(line)
    return out or [""]


# -------------------------------------------------------------------- main

def write_override(name, text):
    os.makedirs(STORE, exist_ok=True)
    existing = load_overrides()
    existing[name] = text
    tmp = OVERRIDES + ".tmp"
    with open(tmp, "w") as fh:
        fh.write("# CCC summary overrides - name<TAB>summary. Edit freely.\n")
        for k in sorted(existing):
            fh.write("%s\t%s\n" % (k, existing[k]))
    os.replace(tmp, OVERRIDES)
    print("  %s %s" % (c(GREEN, "set"), safe_text(name)))


def main(argv):
    args = [a for a in argv]
    if "-h" in args or "--help" in args:
        print(__doc__)
        return
    if "-w" in args:
        i = args.index("-w")
        rest = args[i + 1:]
        if len(rest) < 2:
            sys.exit("usage: CCC -w <project> <summary text>")
        write_override(rest[0], " ".join(rest[1:]))
        return

    alpha = "-a" in args
    only_dirty = "-d" in args
    only_stale = "-s" in args
    long = "-l" in args
    terms = [a for a in args if not a.startswith("-")]

    projects, cached = scan_cached(refresh=("-r" in args))
    CACHED[0] = cached
    now = int(time.time())

    if only_dirty:
        projects = [p for p in projects if p.get("dirty")]
    if only_stale:
        projects = [p for p in projects if p.get("repo") and p["ts"] and (now - p["ts"]) > STALE_DAYS * 86400]
    detail = False
    if terms:
        q = " ".join(terms).lower()
        projects = [p for p in projects
                    if q in p["name"].lower() or q in p["summary"].lower()]
        detail = True

    if not projects:
        print("\n  " + c(DIM, "nothing matched") + "\n")
        return

    if alpha:
        projects.sort(key=lambda p: p["name"].lower())
    else:
        projects.sort(key=lambda p: (p.get("ts") or 0), reverse=True)

    render(projects, long=long, detail=detail)


if __name__ == "__main__":
    main(sys.argv[1:])
