#!/usr/bin/env python3
"""pseudokit: publish under a pseudonym now, prove who you are later.

Every signature is made twice: Ed25519 (small, classical) and SLH-DSA
(FIPS 205, hash-based, post-quantum). A check passes only if both verify.
The link to your real identity is a salted SHA3-512 commitment published in
the persona's genesis file and opened only when you choose.

Needs Python 3.9+ and OpenSSL 3.5+ (for SLH-DSA). Standard library only.
Run `pseudokit.py -h` for commands; see README.md for the workflow.
"""
from __future__ import annotations

import argparse
import base64
import datetime as dt
import functools
import getpass
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

COMMIT_TAG = b"pseudokit-commit-v1\x00"
DEFAULT_SLH = "SLH-DSA-SHAKE-256s"
ALGS = ("ed25519", "slhdsa")
STATEMENT_MARK = "--- statement ---\n"


class KitError(Exception):
    pass


# ---------------------------------------------------------------- OpenSSL

@functools.lru_cache(maxsize=1)
def openssl() -> str:
    exe = os.environ.get("PSEUDOKIT_OPENSSL") or shutil.which("openssl")
    if not exe:
        raise KitError("openssl not found; install OpenSSL 3.5+ or set PSEUDOKIT_OPENSSL")
    out = subprocess.run([exe, "list", "-signature-algorithms"], capture_output=True, text=True)
    if "SLH-DSA" not in out.stdout:
        ver = subprocess.run([exe, "version"], capture_output=True, text=True).stdout.strip()
        raise KitError(f"{exe} ({ver}) has no SLH-DSA; need OpenSSL 3.5+ "
                       "(macOS: brew install openssl@3, then set PSEUDOKIT_OPENSSL)")
    return exe


def ssl(*args: str, check: bool = True) -> subprocess.CompletedProcess:
    r = subprocess.run([openssl(), *args], capture_output=True, stdin=subprocess.DEVNULL)
    # OpenSSL occasionally fails to use a -passin it was given ("unable to get passphrase");
    # the cause is not yet understood, and an identical retry succeeds.
    for _ in range(2):
        if r.returncode == 0 or b"unable to get passphrase" not in r.stderr:
            break
        r = subprocess.run([openssl(), *args], capture_output=True, stdin=subprocess.DEVNULL)
    if check and r.returncode != 0:
        raise KitError(f"openssl {' '.join(args[:2])} failed: {r.stderr.decode(errors='replace').strip()}")
    return r


def ensure_passphrase(key: Path) -> None:
    """Prompt once for the key passphrase if the key is encrypted and none is set."""
    if os.environ.get("PSEUDOKIT_PASS"):
        return
    if b"ENCRYPTED" in key.read_bytes()[:64]:
        os.environ["PSEUDOKIT_PASS"] = getpass.getpass(f"Passphrase for {key.name}: ")


def passin(key: Path) -> list[str]:
    ensure_passphrase(key)
    return ["-passin", "env:PSEUDOKIT_PASS"] if os.environ.get("PSEUDOKIT_PASS") else []


# ---------------------------------------------------------------- layout

class Persona:
    """home/public: keys and genesis anyone may see. home/secret: private keys and the opening."""

    def __init__(self, home: str | None):
        self.home = Path(home or os.environ.get("PSEUDOKIT_HOME") or "persona")
        self.public = self.home / "public"
        self.secret = Path(os.environ["PSEUDOKIT_SECRET"]) if os.environ.get("PSEUDOKIT_SECRET") else self.home / "secret"

    def key(self, alg: str) -> Path:
        return self.secret / f"{alg}.key.pem"

    def pub(self, alg: str) -> Path:
        return self.public / f"{alg}.pub.pem"

    @property
    def info(self) -> dict:
        p = self.public / "persona.json"
        if not p.exists():
            raise KitError(f"no persona at {self.home}; run init first")
        return json.loads(p.read_text())

    @property
    def opening_path(self) -> Path:
        return self.secret / "opening.json"

    @property
    def genesis(self) -> Path:
        return self.public / "genesis.txt"


def write_private(path: Path, data: bytes) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "wb") as f:
        f.write(data)


def today() -> str:
    # Date only, UTC: a time of day would leak your working hours.
    return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%d")


# ---------------------------------------------------------------- primitives

def fingerprint(pub: Path) -> str:
    der = ssl("pkey", "-pubin", "-in", str(pub), "-outform", "DER").stdout
    return "SHA256:" + hashlib.sha256(der).hexdigest()


def sig_path(path: Path, alg: str) -> Path:
    return path.with_name(path.name + f".{alg}.sig")


def sign_file(p: Persona, path: Path) -> list[Path]:
    outs = []
    for alg in ALGS:
        key = p.key(alg)
        out = sig_path(path, alg)
        ssl("pkeyutl", "-sign", "-rawin", "-inkey", str(key), *passin(key), "-in", str(path), "-out", str(out))
        outs.append(out)
    return outs


def verify_file(path: Path, pubdir: Path) -> list[str]:
    """Return a list of problems; empty means both signatures verify."""
    problems = []
    for alg in ALGS:
        sig, pub = sig_path(path, alg), pubdir / f"{alg}.pub.pem"
        if not sig.exists():
            problems.append(f"missing {sig.name}")
            continue
        if not pub.exists():
            problems.append(f"missing {pub}")
            continue
        r = ssl("pkeyutl", "-verify", "-rawin", "-pubin", "-inkey", str(pub),
                "-in", str(path), "-sigfile", str(sig), check=False)
        if r.returncode != 0:
            problems.append(f"{alg} signature does NOT verify")
    return problems


def sign_bytes(p: Persona, data: bytes) -> dict[str, str]:
    with tempfile.TemporaryDirectory() as d:
        m = Path(d) / "msg"
        m.write_bytes(data)
        return {alg: base64.b64encode(s.read_bytes()).decode() for alg, s in zip(ALGS, sign_file(p, m))}


def verify_bytes(data: bytes, sigs: dict[str, str], pubdir: Path) -> list[str]:
    with tempfile.TemporaryDirectory() as d:
        m = Path(d) / "msg"
        m.write_bytes(data)
        for alg in ALGS:
            if alg in sigs:
                sig_path(m, alg).write_bytes(base64.b64decode(sigs[alg]))
        return verify_file(m, pubdir)


def commitment(salt: bytes, statement: str) -> str:
    return "sha3-512:" + hashlib.sha3_512(COMMIT_TAG + salt + statement.encode()).hexdigest()


def fields(text: str) -> dict[str, str]:
    """Parse 'key: value' lines up to the first blank line."""
    out = {}
    for line in text.split("\n"):
        if not line.strip():
            break
        if ": " in line:
            k, v = line.split(": ", 1)
            out[k.strip()] = v.strip()
    return out


def verify_genesis(pubdir: Path) -> dict[str, str]:
    g = pubdir / "genesis.txt"
    if not g.exists():
        raise KitError(f"no genesis.txt in {pubdir}")
    problems = verify_file(g, pubdir)
    text = g.read_text()
    f = fields(text)
    for alg in ALGS:
        pub = pubdir / f"{alg}.pub.pem"
        if not pub.exists():
            continue
        if not f.get(alg, "").startswith(fingerprint(pub)):
            problems.append(f"{alg} key file does not match the fingerprint in genesis.txt")
        if pub.read_text().strip() not in text:
            problems.append(f"{alg} key file differs from the key embedded in genesis.txt")
    if problems:
        raise KitError("genesis check failed:\n  " + "\n  ".join(problems))
    return f


# ---------------------------------------------------------------- commands

def cmd_init(a, p: Persona):
    if p.key("ed25519").exists() or (p.public / "persona.json").exists():
        raise KitError(f"persona already exists at {p.home}")
    p.public.mkdir(parents=True, exist_ok=True)
    p.secret.mkdir(parents=True, exist_ok=True)
    os.chmod(p.secret, 0o700)
    enc = ["-aes-256-cbc", "-pass", "env:PSEUDOKIT_PASS"] if os.environ.get("PSEUDOKIT_PASS") else []
    if not enc:
        print("warning: PSEUDOKIT_PASS not set, private keys are stored unencrypted", file=sys.stderr)
    for alg, name in (("ed25519", "ED25519"), ("slhdsa", a.slh_alg)):
        pem = ssl("genpkey", "-algorithm", name, *enc).stdout
        write_private(p.key(alg), pem)
        pub = ssl("pkey", "-in", str(p.key(alg)), *passin(p.key(alg)), "-pubout").stdout
        p.pub(alg).write_bytes(pub)
    info = {"name": a.name, "slh_alg": a.slh_alg,
            "fingerprints": {alg: fingerprint(p.pub(alg)) for alg in ALGS}}
    (p.public / "persona.json").write_text(json.dumps(info, indent=2) + "\n")
    print(f"persona '{a.name}' created in {p.home}")
    for alg, fp in info["fingerprints"].items():
        print(f"  {alg}: {fp}")
    print(f"Move {p.secret} to encrypted storage (set PSEUDOKIT_SECRET to its new path).")


def cmd_commit(a, p: Persona):
    if p.opening_path.exists() and not a.force:
        raise KitError(f"{p.opening_path} exists; a second commitment would replace it (use --force)")
    info = p.info
    lines = ["pseudokit-identity-v1", f"persona: {info['name']}"]
    lines += [f"{alg}: {info['fingerprints'][alg]}" for alg in ALGS]
    lines += [f"real-name: {a.real_name}", f"real-url: {a.real_url}"]
    if a.note:
        lines.append(f"note: {a.note}")
    statement = "\n".join(lines) + "\n"
    salt = os.urandom(32)
    c = commitment(salt, statement)
    write_private(p.opening_path, (json.dumps(
        {"salt": salt.hex(), "statement": statement, "commitment": c}, indent=2) + "\n").encode())
    print(c)
    print(f"Opening saved to {p.opening_path}. Back it up offline: losing it means you can never "
          "claim the work, and anyone who finds it can unmask you.", file=sys.stderr)


def cmd_genesis(a, p: Persona):
    info = p.info
    c = "none"
    if p.opening_path.exists():
        c = json.loads(p.opening_path.read_text())["commitment"]
    elif not a.no_commitment:
        raise KitError("no identity commitment yet; run commit first (or pass --no-commitment)")
    body = [
        "pseudokit-genesis-v1",
        f"persona: {info['name']}",
        f"date: {today()}",
        f"ed25519: {info['fingerprints']['ed25519']}",
        f"slhdsa: {info['fingerprints']['slhdsa']} ({info['slh_alg']})",
        f"identity-commitment: {c}",
        "",
        "Every file this persona publishes carries an Ed25519 and an SLH-DSA signature by the keys below.",
        "identity-commitment is SHA3-512(\"pseudokit-commit-v1\\0\" || 32-byte salt || statement);",
        "the persona may open it later to show who wrote this.",
        "",
        p.pub("ed25519").read_text().strip(),
        p.pub("slhdsa").read_text().strip(),
        "",
    ]
    p.genesis.write_text("\n".join(body))
    sign_file(p, p.genesis)
    verify_genesis(p.public)
    print(f"wrote and verified {p.genesis} (+ .ed25519.sig, .slhdsa.sig)")
    print("Publish everything in the public/ folder as the persona's first post, then timestamp genesis.txt.")


def cmd_sign(a, p: Persona):
    for f in a.files:
        for s in sign_file(p, Path(f)):
            print(s)


def cmd_verify(a, p: Persona):
    pubdir = Path(a.public) if a.public else p.public
    verify_genesis(pubdir)
    bad = 0
    for f in a.files:
        problems = verify_file(Path(f), pubdir)
        print(f"{'OK  ' if not problems else 'FAIL'} {f}" + ("" if not problems else ": " + "; ".join(problems)))
        bad += bool(problems)
    return 1 if bad else 0


def list_files(root: Path, all_files: bool) -> list[str]:
    if not all_files and (root / ".git").exists():
        out = subprocess.run(["git", "-C", str(root), "ls-files", "-z"], capture_output=True, check=True).stdout
        names = [n for n in out.decode().split("\0") if n]
    else:
        names = []
        for dirpath, dirnames, filenames in os.walk(root):
            dirnames[:] = [d for d in dirnames if d != ".git"]
            for fn in filenames:
                names.append(Path(dirpath, fn).relative_to(root).as_posix())
    return sorted(names)


def sha512_file(path: Path) -> str:
    h = hashlib.sha512()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def cmd_manifest(a, p: Persona):
    root, out = Path(a.dir), Path(a.out)
    skip = {out.resolve()} | {sig_path(out, alg).resolve() for alg in ALGS}
    entries = []
    for name in list_files(root, a.all_files):
        f = root / name
        if f.resolve() in skip:
            continue
        if "\n" in name or "\r" in name:
            raise KitError(f"file name with a newline: {name!r}")
        if f.is_symlink():
            raise KitError(f"symlinks are not supported: {name}")
        if not f.is_file():
            continue  # e.g. a tracked file deleted in the working tree, or a submodule
        entries.append(f"{sha512_file(f)}  {name}")
    head = ["pseudokit-manifest-v1", f"persona: {p.info['name']}", f"date: {today()}"]
    if (root / ".git").exists():
        r = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True)
        if r.returncode == 0:
            head.append(f"git-head: {r.stdout.strip()} (a SHA-1 id; the SHA-512 lines below are the binding)")
    head.append(f"files: {len(entries)}")
    out.write_text("\n".join(head) + "\n\n" + "\n".join(entries) + "\n")
    sign_file(p, out)
    print(f"wrote {out} ({len(entries)} files) with both signatures")


def cmd_verify_manifest(a, p: Persona):
    pubdir = Path(a.public) if a.public else p.public
    g = verify_genesis(pubdir)
    man, root = Path(a.manifest), Path(a.dir)
    problems = verify_file(man, pubdir)
    text = man.read_text()
    f = fields(text)
    if f.get("persona") != g.get("persona"):
        problems.append(f"manifest persona {f.get('persona')!r} != genesis persona {g.get('persona')!r}")
    listed = set()
    body = text.split("\n\n", 1)[1] if "\n\n" in text else ""
    for line in body.splitlines():
        if not line:
            continue
        digest, name = line.split("  ", 1)
        listed.add(name)
        path = root / name
        if not path.is_file():
            problems.append(f"missing: {name}")
        elif sha512_file(path) != digest:
            problems.append(f"changed: {name}")
    if f.get("files") != str(len(listed)):
        problems.append("file count in header does not match the list")
    for p_ in problems:
        print("FAIL", p_)
    if not problems:
        print(f"OK  {len(listed)} files match {man.name}, signed by persona '{g['persona']}'")
    return 1 if problems else 0


def challenge_message(persona: str, nonce: str) -> bytes:
    return f"pseudokit-challenge-v1\npersona: {persona}\nnonce: {nonce}\n".encode()


def cmd_challenge(a, p: Persona):
    name = p.info["name"]
    blob = {"format": "pseudokit-challenge-v1", "persona": name, "nonce": a.nonce,
            "sigs": sign_bytes(p, challenge_message(name, a.nonce))}
    Path(a.out).write_text(json.dumps(blob) + "\n")
    print(f"wrote {a.out}; send it to the person who gave you the nonce")


def cmd_verify_challenge(a, p: Persona):
    pubdir = Path(a.public) if a.public else p.public
    g = verify_genesis(pubdir)
    blob = json.loads(Path(a.file).read_text())
    problems = []
    if blob.get("nonce") != a.nonce:
        problems.append("nonce does not match the one you issued")
    if blob.get("persona") != g["persona"]:
        problems.append("persona name does not match genesis")
    problems += verify_bytes(challenge_message(g["persona"], a.nonce), blob.get("sigs", {}), pubdir)
    for x in problems:
        print("FAIL", x)
    if not problems:
        print(f"OK  the holder of persona '{g['persona']}' signed your nonce")
    return 1 if problems else 0


def cmd_reveal(a, p: Persona):
    g = verify_genesis(p.public)
    op = json.loads(p.opening_path.read_text())
    salt, statement = bytes.fromhex(op["salt"]), op["statement"]
    if commitment(salt, statement) != g.get("identity-commitment"):
        raise KitError("opening does not match the commitment in genesis.txt")
    out = Path(a.out)
    out.mkdir(parents=True, exist_ok=True)
    reveal = out / "reveal.txt"
    reveal.write_text(
        "pseudokit-reveal-v1\n"
        f"persona: {g['persona']}\n"
        f"identity-commitment: {g['identity-commitment']}\n"
        f"salt: {op['salt']}\n"
        f"date: {today()}\n\n" + STATEMENT_MARK + statement)
    sign_file(p, reveal)
    shutil.copytree(p.public, out / "public", dirs_exist_ok=True)
    sf = fields(statement.split("\n", 1)[1])
    (out / "real-channel-post.txt").write_text(
        f"I am the author behind the pseudonym '{g['persona']}'.\n"
        f"Persona keys: ed25519 {g['ed25519']}, slhdsa {g['slhdsa']}\n"
        f"The persona's genesis committed to this on {g.get('date')}: {g['identity-commitment']}\n"
        f"The persona-signed opening is in the attached reveal bundle.\n"
        f"-- {sf.get('real-name')} ({sf.get('real-url')})\n")
    print(f"wrote reveal bundle to {out}")
    print("1. Post real-channel-post.txt from your real-name account (that's what proves the real side).")
    print("2. Publish the bundle from the persona. Anyone can then run verify-reveal on it.")


def cmd_verify_reveal(a, p: Persona):
    out = Path(a.bundle)
    g = verify_genesis(out / "public")
    reveal = out / "reveal.txt"
    problems = verify_file(reveal, out / "public")
    # A bundle is self-consistent by construction; what matters is that its genesis
    # is the one the persona published long ago, not a fresh one made for the reveal.
    bundle_genesis = (out / "public" / "genesis.txt").read_bytes()
    if a.public:
        known = Path(a.public) / "genesis.txt"
        if not known.exists() or known.read_bytes() != bundle_genesis:
            problems.append(f"bundle genesis differs from the known genesis at {known}")
    text = reveal.read_text()
    f = fields(text)
    if STATEMENT_MARK not in text:
        raise KitError("reveal.txt has no statement")
    statement = text.split(STATEMENT_MARK, 1)[1]
    c = commitment(bytes.fromhex(f["salt"]), statement)
    if c != g["identity-commitment"]:
        problems.append("salt + statement do not hash to the commitment in genesis.txt")
    if f.get("identity-commitment") != g["identity-commitment"]:
        problems.append("reveal names a different commitment than genesis")
    sf = fields(statement.split("\n", 1)[1]) if "\n" in statement else {}
    if sf.get("persona") != g["persona"]:
        problems.append("statement names a different persona")
    for alg in ALGS:
        if not g.get(alg, "").startswith(sf.get(alg, "-")):
            problems.append(f"statement {alg} fingerprint does not match genesis")
    for x in problems:
        print("FAIL", x)
    if problems:
        return 1
    print(f"OK  persona '{g['persona']}' (genesis dated {g.get('date')}) committed to:")
    print(f"    real-name: {sf.get('real-name')}\n    real-url:  {sf.get('real-url')}")
    print(f"genesis.txt SHA-256: {hashlib.sha256(bundle_genesis).hexdigest()}"
          + ("  (matches your known copy)" if a.public else ""))
    if not a.public:
        print("Not checked: that this genesis is the one the persona published originally. "
              "Re-run with --public <persona's published folder>.")
    print("Still check: a matching post at real-url from the real-name account, and the timestamp proof of genesis.txt.")
    return 0


# ---------------------------------------------------------------- CLI

def main(argv=None) -> int:
    ap = argparse.ArgumentParser(prog="pseudokit", description=__doc__.split("\n\n")[0])
    ap.add_argument("--home", help="persona folder (default $PSEUDOKIT_HOME or ./persona)")
    sub = ap.add_subparsers(dest="cmd", required=True)

    s = sub.add_parser("init", help="create the persona's Ed25519 and SLH-DSA keys")
    s.add_argument("--name", required=True)
    s.add_argument("--slh-alg", default=DEFAULT_SLH, help=f"default {DEFAULT_SLH}")
    s.set_defaults(fn=cmd_init)

    s = sub.add_parser("commit", help="commit (hidden) to your real identity")
    s.add_argument("--real-name", required=True)
    s.add_argument("--real-url", required=True, help="where your real-name account will confirm it")
    s.add_argument("--note", default="")
    s.add_argument("--force", action="store_true")
    s.set_defaults(fn=cmd_commit)

    s = sub.add_parser("genesis", help="write and sign the persona's first public file")
    s.add_argument("--no-commitment", action="store_true")
    s.set_defaults(fn=cmd_genesis)

    s = sub.add_parser("sign", help="sign files with both keys")
    s.add_argument("files", nargs="+")
    s.set_defaults(fn=cmd_sign)

    s = sub.add_parser("verify", help="verify files' signatures against a genesis")
    s.add_argument("files", nargs="+")
    s.add_argument("--public", help="folder with genesis.txt and the public keys")
    s.set_defaults(fn=cmd_verify)

    s = sub.add_parser("manifest", help="SHA-512 every file in a release and sign the list")
    s.add_argument("dir")
    s.add_argument("--out", required=True)
    s.add_argument("--all-files", action="store_true", help="in a git repo, include untracked files too")
    s.set_defaults(fn=cmd_manifest)

    s = sub.add_parser("verify-manifest", help="check a release against its signed manifest")
    s.add_argument("manifest")
    s.add_argument("--dir", required=True)
    s.add_argument("--public")
    s.set_defaults(fn=cmd_verify_manifest)

    s = sub.add_parser("challenge", help="sign a verifier's nonce (private proof, names no one)")
    s.add_argument("nonce")
    s.add_argument("--out", default="challenge.json")
    s.set_defaults(fn=cmd_challenge)

    s = sub.add_parser("verify-challenge", help="check a signed nonce")
    s.add_argument("file")
    s.add_argument("--nonce", required=True, help="the nonce you issued")
    s.add_argument("--public")
    s.set_defaults(fn=cmd_verify_challenge)

    s = sub.add_parser("reveal", help="build the bundle that opens the identity commitment")
    s.add_argument("--out", required=True)
    s.set_defaults(fn=cmd_reveal)

    s = sub.add_parser("verify-reveal", help="check a reveal bundle")
    s.add_argument("bundle")
    s.add_argument("--public", help="the persona's originally published folder, to compare genesis against")
    s.set_defaults(fn=cmd_verify_reveal)

    a = ap.parse_args(argv)
    try:
        return a.fn(a, Persona(a.home)) or 0
    except KitError as e:
        print(f"error: {e}", file=sys.stderr)
        return 2


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