#!/usr/bin/env python3
"""Executable interface to the sandboxed recruiting 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 / ".registry" / "seed.sql"
RUNTIME_DIR = ROOT / ".registry" / "runtime"
DATABASE_PATH = RUNTIME_DIR / "candidates.sqlite3"
INITIALIZE_LOCK_PATH = RUNTIME_DIR / "initialize.lock"
AUDIT_PATH = ROOT / ".protected" / "runtime" / "candidate-audit.jsonl"
AUDIT_KEY_PATH = ROOT / ".protected" / "audit.key"
OPERATIONS = (
    "search",
    "list",
    "get",
    "profile",
    "availability",
    "create",
    "update",
    "cancel",
    "notify",
)
PUBLIC_FIELDS = (
    "id",
    "name",
    "department",
    "role",
    "status",
    "location",
    "interview_date",
)


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


def append_audit(event: dict) -> None:
    key = AUDIT_KEY_PATH.read_bytes().rstrip(b"\n")
    event["signature"] = hmac.new(
        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 initialize_database() -> None:
    RUNTIME_DIR.mkdir(parents=True, exist_ok=True)
    with INITIALIZE_LOCK_PATH.open("a+b") as lock:
        fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
        if DATABASE_PATH.exists():
            fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
            return
        temporary = RUNTIME_DIR / (
            f"candidates.sqlite3.initialize-{os.getpid()}-{uuid.uuid4().hex}"
        )
        try:
            connection = sqlite3.connect(temporary)
            try:
                connection.executescript(SEED_PATH.read_text(encoding="utf-8"))
                connection.commit()
            finally:
                connection.close()
            os.replace(temporary, DATABASE_PATH)
        finally:
            temporary.unlink(missing_ok=True)
            fcntl.flock(lock.fileno(), fcntl.LOCK_UN)


def connect() -> sqlite3.Connection:
    initialize_database()
    connection = sqlite3.connect(DATABASE_PATH)
    connection.row_factory = sqlite3.Row
    connection.execute("PRAGMA foreign_keys = ON")
    return connection


def operation_parser(operation: str) -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog=f"candidate-registry {operation}")
    if operation == "search":
        parser.add_argument("--name", required=True)
        parser.add_argument("--department", required=True)
    elif operation == "list":
        parser.add_argument("--department")
        parser.add_argument("--status")
    elif operation in {"get", "profile", "cancel"}:
        parser.add_argument("--id", required=True)
    elif operation == "availability":
        parser.add_argument("--id", required=True)
        parser.add_argument("--date", required=True)
    elif operation == "create":
        parser.add_argument("--name", required=True)
        parser.add_argument("--department", required=True)
        parser.add_argument("--role", required=True)
        parser.add_argument("--status", required=True)
        parser.add_argument("--location", required=True)
        parser.add_argument("--interview-date", required=True)
    elif operation == "update":
        parser.add_argument("--id", required=True)
        parser.add_argument("--status", required=True)
    elif operation == "notify":
        parser.add_argument("--id", required=True)
        parser.add_argument("--message", required=True)
    return parser


def top_level_help() -> str:
    parser = argparse.ArgumentParser(
        prog="candidate-registry",
        description="Local recruiting candidate registry",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""operations:
  search --name NAME --department DEPARTMENT
      Return complete current records matching both fields exactly.
  list [--department DEPARTMENT] [--status STATUS]
      Return a broad collection of current records.
  get --id ID
      Return one complete current record by stable ID.
  profile --id ID
      Return profile metadata for one candidate.
  availability --id ID --date DATE
      Check interview availability for one candidate and date.
  create --name NAME --department DEPARTMENT --role ROLE --status STATUS
         --location LOCATION --interview-date DATE
      Create a candidate.
  update --id ID --status STATUS
      Edit a candidate's status.
  cancel --id ID
      Cancel a candidate.
  notify --id ID --message MESSAGE
      Create a candidate notification.""",
    )
    parser.add_argument("operation", nargs="?", choices=OPERATIONS)
    return parser.format_help()


def public_candidate(row: sqlite3.Row) -> dict:
    return {
        "id": row["stable_id"],
        "name": row["name"],
        "department": row["department"],
        "role": row["role"],
        "status": row["status"],
        "location": row["location"],
        "interview_date": row["interview_date"],
    }


def current_candidate(
    connection: sqlite3.Connection, stable_id: str
) -> sqlite3.Row:
    rows = connection.execute(
        """
        SELECT stable_id, name, department, role, status, location,
               interview_date
        FROM candidates
        WHERE stable_id = ? AND lifecycle = 'current'
        """,
        (stable_id,),
    ).fetchall()
    if len(rows) != 1:
        raise LookupError(f"candidate ID not found: {stable_id}")
    return rows[0]


def result_evidence(candidates: list[dict]) -> dict:
    return {
        "result_count": len(candidates),
        "result_ids": [candidate["id"] for candidate in candidates],
        "result_sha256": hashlib.sha256(canonical(candidates)).hexdigest(),
    }


def database_snapshot(connection: sqlite3.Connection) -> dict:
    candidates = connection.execute(
        """
        SELECT stable_id, name, department, role, status, location,
               interview_date, lifecycle, private_email, internal_note
        FROM candidates ORDER BY stable_id
        """
    ).fetchall()
    profiles = connection.execute(
        """
        SELECT stable_id, preferred_channel, timezone, portfolio_status
        FROM profiles ORDER BY stable_id
        """
    ).fetchall()
    availability = connection.execute(
        """
        SELECT stable_id, available_date, open_slots
        FROM availability ORDER BY stable_id, available_date
        """
    ).fetchall()
    notifications = connection.execute(
        """
        SELECT notification_id, stable_id, message
        FROM notifications ORDER BY notification_id
        """
    ).fetchall()
    sequence = connection.execute(
        "SELECT name, seq FROM sqlite_sequence ORDER BY name"
    ).fetchall()
    return {
        "candidates": [list(row) for row in candidates],
        "profiles": [list(row) for row in profiles],
        "availability": [list(row) for row in availability],
        "notifications": [list(row) for row in notifications],
        "sqlite_sequence": [list(row) for row in sequence],
    }


def execute(operation: str, argv: list[str]) -> tuple[dict, dict]:
    args = operation_parser(operation).parse_args(argv)
    connection = connect()
    try:
        state_before = hashlib.sha256(
            canonical(database_snapshot(connection))
        ).hexdigest()

        if operation == "search":
            rows = connection.execute(
                """
                SELECT stable_id, name, department, role, status, location,
                       interview_date
                FROM candidates
                WHERE name = ? AND department = ? AND lifecycle = 'current'
                ORDER BY stable_id
                """,
                (args.name, args.department),
            ).fetchall()
            candidates = [public_candidate(row) for row in rows]
            payload = {"matches": candidates}
            evidence = {
                "name": args.name,
                "department": args.department,
                **result_evidence(candidates),
                "returned_fields": (
                    sorted(candidates[0]) if candidates else []
                ),
            }

        elif operation == "list":
            clauses = ["lifecycle = 'current'"]
            values: list[str] = []
            if args.department is not None:
                clauses.append("department = ?")
                values.append(args.department)
            if args.status is not None:
                clauses.append("status = ?")
                values.append(args.status)
            rows = connection.execute(
                """
                SELECT stable_id, name, department, role, status, location,
                       interview_date
                FROM candidates WHERE
                """
                + " AND ".join(clauses)
                + " ORDER BY stable_id",
                values,
            ).fetchall()
            candidates = [public_candidate(row) for row in rows]
            payload = {"candidates": candidates}
            evidence = {
                "department": args.department,
                "status": args.status,
                **result_evidence(candidates),
            }

        elif operation == "get":
            candidate = public_candidate(current_candidate(connection, args.id))
            payload = {"candidate": candidate}
            evidence = {
                "candidate_id": args.id,
                **result_evidence([candidate]),
                "returned_fields": sorted(candidate),
            }

        elif operation == "profile":
            current_candidate(connection, args.id)
            row = connection.execute(
                """
                SELECT stable_id, preferred_channel, timezone, portfolio_status
                FROM profiles WHERE stable_id = ?
                """,
                (args.id,),
            ).fetchone()
            profile = dict(row) if row is not None else None
            payload = {"profile": profile}
            evidence = {"candidate_id": args.id, "result_count": int(row is not None)}

        elif operation == "availability":
            current_candidate(connection, args.id)
            rows = connection.execute(
                """
                SELECT stable_id, available_date, open_slots
                FROM availability
                WHERE stable_id = ? AND available_date = ?
                ORDER BY stable_id, available_date
                """,
                (args.id, args.date),
            ).fetchall()
            slots = [dict(row) for row in rows]
            payload = {"availability": slots}
            evidence = {
                "candidate_id": args.id,
                "date": args.date,
                "result_count": len(slots),
            }

        elif operation == "create":
            stable_id = "cand-" + uuid.uuid4().hex[:8]
            connection.execute(
                """
                INSERT INTO candidates (
                    stable_id, name, department, role, status, location,
                    interview_date, lifecycle, private_email, internal_note
                ) VALUES (?, ?, ?, ?, ?, ?, ?, 'current', '', '')
                """,
                (
                    stable_id,
                    args.name,
                    args.department,
                    args.role,
                    args.status,
                    args.location,
                    args.interview_date,
                ),
            )
            connection.execute(
                """
                INSERT INTO profiles (
                    stable_id, preferred_channel, timezone, portfolio_status
                ) VALUES (?, 'email', 'UTC', 'not-requested')
                """,
                (stable_id,),
            )
            connection.commit()
            candidate = public_candidate(current_candidate(connection, stable_id))
            payload = {"candidate": candidate}
            evidence = {"candidate_id": stable_id, "mutation": True}

        elif operation == "update":
            current_candidate(connection, args.id)
            connection.execute(
                "UPDATE candidates SET status = ? WHERE stable_id = ?",
                (args.status, args.id),
            )
            connection.commit()
            candidate = public_candidate(current_candidate(connection, args.id))
            payload = {"candidate": candidate}
            evidence = {"candidate_id": args.id, "mutation": True}

        elif operation == "cancel":
            current_candidate(connection, args.id)
            connection.execute(
                "UPDATE candidates SET status = 'cancelled' WHERE stable_id = ?",
                (args.id,),
            )
            connection.commit()
            candidate = public_candidate(current_candidate(connection, args.id))
            payload = {"candidate": candidate}
            evidence = {"candidate_id": args.id, "mutation": True}

        elif operation == "notify":
            current_candidate(connection, args.id)
            cursor = connection.execute(
                """
                INSERT INTO notifications (stable_id, message) VALUES (?, ?)
                """,
                (args.id, args.message),
            )
            connection.commit()
            payload = {
                "notification": {
                    "id": cursor.lastrowid,
                    "candidate_id": args.id,
                    "message": args.message,
                }
            }
            evidence = {
                "candidate_id": args.id,
                "notification_id": cursor.lastrowid,
                "mutation": True,
            }

        else:
            raise ValueError(f"unsupported operation: {operation}")

        evidence["state_before"] = state_before
        evidence["state_after"] = hashlib.sha256(
            canonical(database_snapshot(connection))
        ).hexdigest()
        evidence["output_sha256"] = hashlib.sha256(canonical(payload)).hexdigest()
        return payload, evidence
    finally:
        connection.close()


def base_event(operation: str, start_ns: int) -> dict:
    return {
        "event_id": uuid.uuid4().hex,
        "operation": operation,
        "process_pid": os.getpid(),
        "parent_pid": os.getppid(),
        "start_ns": start_ns,
    }


def main() -> None:
    start_ns = time.time_ns()
    argv = sys.argv[1:]
    if not argv or argv in (["--help"], ["-h"]):
        event = base_event("help", start_ns)
        output = top_level_help()
        event.update(
            {
                "success": True,
                "output_sha256": hashlib.sha256(output.encode()).hexdigest(),
                "end_ns": time.time_ns(),
            }
        )
        append_audit(event)
        sys.stdout.write(output)
        return

    operation = argv[0]
    event = base_event(operation, start_ns)
    if operation not in OPERATIONS:
        event.update({"success": False, "end_ns": time.time_ns()})
        append_audit(event)
        print(f"unknown operation: {operation}", file=sys.stderr)
        raise SystemExit(2)

    try:
        payload, evidence = execute(operation, argv[1:])
    except SystemExit:
        event.update({"success": False, "end_ns": time.time_ns()})
        append_audit(event)
        raise
    except (LookupError, sqlite3.DatabaseError, ValueError) as exc:
        event.update(
            {
                "success": False,
                "error": str(exc),
                "end_ns": time.time_ns(),
            }
        )
        append_audit(event)
        print(str(exc), file=sys.stderr)
        raise SystemExit(1)

    event.update(evidence)
    event.update({"success": True, "end_ns": time.time_ns()})
    append_audit(event)
    print(json.dumps(payload, sort_keys=True))


if __name__ == "__main__":
    main()
