#!/usr/bin/env python3
"""Copy the OpenCode Go key from the desktop app store into the CLI auth files.

The OpenCode desktop app writes its login to
    <XDG_DATA_HOME>/opencode/opencode.db  (table credential, integration opencode-go)
but the opencode CLI, firstmate workers, pi, and no-mistakes read
    <XDG_DATA_HOME>/opencode/auth.json    (opencode-go.key)
    ~/.pi/agent/auth.json                 (opencode-go.key)

After an account switch the app store is current and those JSON files still hold
the old key, so workers and the validation pipeline fail with a usage or auth
error. Run this after switching accounts.

Safety:
  * The app credential is the source only when it is newer than the target file.
  * If a target file is newer than the app credential, it is left alone and the
    command reports a conflict instead of overwriting a manual login.
  * The key is never printed.

Exit status: 0 in sync or updated, 2 conflict, 1 no source credential.
"""

import argparse
import json
import os
import sqlite3
import sys
import tempfile
import time


def data_home():
    return os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")


def app_credential():
    db = os.path.join(data_home(), "opencode", "opencode.db")
    if not os.path.exists(db):
        return None
    con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
    try:
        row = con.execute(
            "select value, time_updated from credential"
            " where integration_id='opencode-go' order by time_updated desc limit 1"
        ).fetchone()
    finally:
        con.close()
    if not row:
        return None
    try:
        payload = json.loads(row[0])
    except Exception:
        return None
    key = payload.get("key") if isinstance(payload, dict) else None
    if not key:
        return None
    return key, int(row[1]) / 1000.0


def read_target(path):
    with open(path) as fh:
        data = json.load(fh)
    entry = data.get("opencode-go")
    key = entry.get("key") if isinstance(entry, dict) else None
    return data, key


def write_target(path, data):
    directory = os.path.dirname(path)
    fd, tmp = tempfile.mkstemp(dir=directory, prefix=".auth.", suffix=".json")
    try:
        with os.fdopen(fd, "w") as fh:
            json.dump(data, fh)
        os.chmod(tmp, 0o600)
        os.replace(tmp, path)
    finally:
        if os.path.exists(tmp):
            os.unlink(tmp)


def target_paths():
    return [
        os.path.join(data_home(), "opencode", "auth.json"),
        os.path.expanduser("~/.pi/agent/auth.json"),
    ]


def sync_hermes(source_key, check):
    """Update OPENCODE_GO_API_KEY in the Hermes env file when it differs."""
    path = os.path.expanduser("~/.hermes/.env")
    if not os.path.exists(path):
        return 0
    with open(path) as fh:
        lines = fh.readlines()
    current = None
    for line in lines:
        stripped = line.rstrip("\n")
        if stripped.startswith("OPENCODE_GO_API_KEY="):
            current = stripped.split("=", 1)[1]
            break
    if current is None:
        return 0
    label = "hermes/.env"
    if current == source_key:
        print(f"{label}: in sync")
        return 0
    if check:
        print(f"{label}: stale, would update", file=sys.stderr)
        return 2
    rewritten = []
    for line in lines:
        if line.startswith("OPENCODE_GO_API_KEY="):
            rewritten.append(f"OPENCODE_GO_API_KEY={source_key}\n")
        else:
            rewritten.append(line)
    with open(path, "w") as fh:
        fh.writelines(rewritten)
    os.chmod(path, 0o600)
    print(f"{label}: updated")
    return 0


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--check",
        action="store_true",
        help="report drift and exit 2 instead of updating",
    )
    args = parser.parse_args()

    source = app_credential()
    if not source:
        print(
            "opencode-go-key-sync: no opencode-go credential in the app store",
            file=sys.stderr,
        )
        return 1
    source_key, source_time = source

    status = 0
    for path in target_paths():
        label = os.path.basename(os.path.dirname(path)) + "/" + os.path.basename(path)
        if not os.path.exists(path):
            print(f"{label}: missing, skipped", file=sys.stderr)
            status = max(status, 2)
            continue
        data, current_key = read_target(path)
        if current_key == source_key:
            print(f"{label}: in sync")
            continue
        target_time = os.path.getmtime(path)
        if target_time > source_time:
            print(
                f"{label}: has a newer key than the app store, left unchanged"
                " (log in again in the app, or update this file by hand)",
                file=sys.stderr,
            )
            status = max(status, 2)
            continue
        if args.check:
            print(f"{label}: stale, would update", file=sys.stderr)
            status = max(status, 2)
            continue
        entry = data.get("opencode-go")
        if not isinstance(entry, dict):
            entry = {"type": "api"}
        entry["key"] = source_key
        data["opencode-go"] = entry
        write_target(path, data)
        print(f"{label}: updated")

    status = max(status, sync_hermes(source_key, args.check))
    return status


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