#!/usr/bin/env python3
"""Executable interface to the sandboxed support-case registry."""

from __future__ import annotations

import argparse
import fcntl
import hashlib
import hmac
import json
import os
from pathlib import Path
import sqlite3
import sys
import time
import uuid


ROOT = Path(__file__).resolve().parent
SEED_PATH = ROOT / ".support" / "seed.sql"
REGISTRY_RUNTIME = ROOT / ".support" / "runtime"
DATABASE_PATH = REGISTRY_RUNTIME / "support.sqlite3"
INITIALIZE_LOCK_PATH = REGISTRY_RUNTIME / "initialize.lock"
AUDIT_PATH = ROOT / ".harness" / "runtime" / "support-audit.jsonl"
REFERENCE_MARKER = ROOT / ".reference_solution"
AUDIT_KEY = b"moonshiner-pi-support-audit-format-0005-v1"
OPERATIONS = ("get", "search", "list", "profile", "update", "cancel", "notify")


def canonical(value: dict) -> bytes:
    return json.dumps(value, sort_keys=True, separators=(",", ":")).encode()


def process_start_ticks(process_pid: int) -> str:
    try:
        stat = Path(f"/proc/{process_pid}/stat").read_text(encoding="utf-8")
        return stat.rsplit(") ", 1)[1].split()[19]
    except (OSError, IndexError):
        return "unavailable"


def append_audit(event: dict) -> None:
    event["signature"] = hmac.new(
        AUDIT_KEY, canonical(event), hashlib.sha256
    ).hexdigest()
    AUDIT_PATH.parent.mkdir(parents=True, exist_ok=True)
    with AUDIT_PATH.open("a", encoding="utf-8") as stream:
        fcntl.flock(stream.fileno(), fcntl.LOCK_EX)
        stream.write(json.dumps(event, sort_keys=True, separators=(",", ":")) + "\n")
        stream.flush()
        os.fsync(stream.fileno())
        fcntl.flock(stream.fileno(), fcntl.LOCK_UN)


def ensure_database() -> None:
    REGISTRY_RUNTIME.mkdir(parents=True, exist_ok=True)
    with INITIALIZE_LOCK_PATH.open("a", encoding="utf-8") as lock:
        fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
        if not DATABASE_PATH.exists():
            temporary = REGISTRY_RUNTIME / f"support-{os.getpid()}.sqlite3.tmp"
            temporary.unlink(missing_ok=True)
            connection = sqlite3.connect(temporary)
            try:
                connection.executescript(SEED_PATH.read_text(encoding="utf-8"))
                connection.commit()
            finally:
                connection.close()
            os.replace(temporary, DATABASE_PATH)
        fcntl.flock(lock.fileno(), fcntl.LOCK_UN)


def operation_parser(operation: str) -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog=f"support-case {operation}")
    if operation in {"get", "profile", "cancel"}:
        parser.add_argument("--id", dest="stable_id", required=True)
    elif operation == "search":
        parser.add_argument("--name", required=True)
    elif operation == "update":
        parser.add_argument("--id", dest="stable_id", required=True)
        parser.add_argument("--status", required=True)
    elif operation == "notify":
        parser.add_argument("--id", dest="stable_id", required=True)
        parser.add_argument("--message", required=True)
    return parser


def full_record(connection: sqlite3.Connection, stable_id: str) -> dict:
    row = connection.execute(
        """
        SELECT stable_id, name, location, status, opened_on, priority,
               description, lifecycle
        FROM cases
        WHERE stable_id = ? AND lifecycle = 'current'
        """,
        (stable_id,),
    ).fetchone()
    if row is None:
        raise LookupError(f"current stable ID not found: {stable_id}")
    return {
        "id": row[0],
        "name": row[1],
        "location": row[2],
        "status": row[3],
        "opened_on": row[4],
        "priority": row[5],
        "description": row[6],
        "lifecycle": row[7],
    }


def execute(operation: str, argv: list[str]) -> tuple[dict, dict]:
    ensure_database()
    args = operation_parser(operation).parse_args(argv)
    connection = sqlite3.connect(DATABASE_PATH, timeout=10)
    try:
        if operation == "get":
            record = full_record(connection, args.stable_id)
            return {"case": record}, {
                "stable_id": args.stable_id,
                "argument_type": type(args.stable_id).__name__,
                "result_count": 1,
                "result_id": record["id"],
                "result_fields": sorted(record),
            }

        if operation == "search":
            rows = connection.execute(
                """
                SELECT stable_id, name, location
                FROM cases
                WHERE name = ? AND lifecycle = 'current'
                ORDER BY stable_id
                """,
                (args.name,),
            ).fetchall()
            matches = [
                {"id": row[0], "name": row[1], "location": row[2]} for row in rows
            ]
            return {"matches": matches}, {
                "name": args.name,
                "result_count": len(matches),
                "result_ids": [match["id"] for match in matches],
            }

        if operation == "list":
            rows = connection.execute(
                """
                SELECT stable_id, name
                FROM cases
                WHERE lifecycle = 'current'
                ORDER BY stable_id
                """
            ).fetchall()
            cases = [{"id": row[0], "name": row[1]} for row in rows]
            return {"cases": cases}, {"result_count": len(cases)}

        if operation == "profile":
            record = full_record(connection, args.stable_id)
            profile = {
                "id": record["id"],
                "name": record["name"],
                "location": record["location"],
            }
            return {"profile": profile}, {
                "stable_id": args.stable_id,
                "argument_type": type(args.stable_id).__name__,
                "result_count": 1,
                "result_id": record["id"],
            }

        if operation == "update":
            full_record(connection, args.stable_id)
            connection.execute(
                "UPDATE cases SET status = ? WHERE stable_id = ?",
                (args.status, args.stable_id),
            )
            connection.commit()
            record = full_record(connection, args.stable_id)
            return {"case": record}, {
                "stable_id": args.stable_id,
                "argument_type": type(args.stable_id).__name__,
                "result_count": 1,
                "result_id": record["id"],
            }

        if operation == "cancel":
            full_record(connection, args.stable_id)
            connection.execute(
                "UPDATE cases SET lifecycle = 'cancelled' WHERE stable_id = ?",
                (args.stable_id,),
            )
            connection.commit()
            return {"cancelled": args.stable_id}, {
                "stable_id": args.stable_id,
                "argument_type": type(args.stable_id).__name__,
                "result_count": 1,
                "result_id": args.stable_id,
            }

        if operation == "notify":
            full_record(connection, args.stable_id)
            cursor = connection.execute(
                "INSERT INTO notifications (stable_id, message) VALUES (?, ?)",
                (args.stable_id, args.message),
            )
            connection.commit()
            return {
                "notification": {
                    "notification_id": cursor.lastrowid,
                    "id": args.stable_id,
                    "message": args.message,
                }
            }, {
                "stable_id": args.stable_id,
                "argument_type": type(args.stable_id).__name__,
                "result_count": 1,
                "result_id": args.stable_id,
            }
    finally:
        connection.close()

    raise ValueError(f"operation is unavailable: {operation}")


def usage() -> None:
    print(
        "usage: support-case {" + ",".join(OPERATIONS) + "} ...",
        file=sys.stderr,
    )


def main() -> int:
    if len(sys.argv) == 1 or sys.argv[1] in {"-h", "--help"}:
        usage()
        return 2

    operation = sys.argv[1]
    start_ns = time.monotonic_ns()
    parent_pid = os.getppid()
    details: dict = {}
    output: dict | None = None
    error: str | None = None
    success = False

    try:
        if operation not in OPERATIONS:
            raise ValueError(f"operation is unavailable: {operation}")
        output, details = execute(operation, sys.argv[2:])
        success = True
    except (
        SystemExit,
        ValueError,
        LookupError,
        OSError,
        sqlite3.DatabaseError,
    ) as exc:
        error = str(exc)

    end_ns = time.monotonic_ns()
    event = {
        "event_id": str(uuid.uuid4()),
        "operation": operation,
        "start_ns": start_ns,
        "end_ns": end_ns,
        "process_pid": os.getpid(),
        "process_start_ticks": process_start_ticks(os.getpid()),
        "process_group_id": os.getpgrp(),
        "session_id": os.getsid(0),
        "parent_pid": parent_pid,
        "parent_start_ticks": process_start_ticks(parent_pid),
        "reference_marker": REFERENCE_MARKER.is_file(),
        "success": success,
        **details,
    }
    if error is not None:
        event["error"] = error
    append_audit(event)

    if success:
        print(json.dumps(output, sort_keys=True))
        return 0
    print(json.dumps({"error": error or "operation failed"}), file=sys.stderr)
    return 2


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