/*
 * Copyright 2026 Goondocks.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { getDatabase } from '@myco/db/client.js';
import {
  getCanopyDescribeBacklog,
  type CanopyDescribeBacklog,
} from '@myco/db/queries/canopy.js';
import type { ProjectScope } from '@myco/grove/ids.js';
import { resolveMycoHome } from '@myco/grove/paths.js';
import { listRegisteredProjects, loadGroveRecord } from '@myco/grove/registry.js';

export interface CanopyDescribeBacklogContext {
  /** Grove the request is bound to; consulted for grove-wide reads. */
  groveId?: string | null;
}

export interface CanopyDescribeBacklogReader {
  read(scope: ProjectScope, context?: CanopyDescribeBacklogContext): CanopyDescribeBacklog;
}

export interface CanopyDescribeBacklogReaderOptions {
  mycoHome?: string;
}

export function createCanopyDescribeBacklogReader(
  options: CanopyDescribeBacklogReaderOptions = {},
): CanopyDescribeBacklogReader {
  return {
    read(scope, context) {
      const projectIds = scope.kind === 'all'
        ? serviceableProjectIds(context?.groveId ?? null, options.mycoHome)
        : null;
      return getCanopyDescribeBacklog(
        getDatabase(),
        scope,
        projectIds ? { projectIds } : {},
      );
    },
  };
}

// Grove-wide backlog counts must reflect work the scribe can actually
// service: active registered projects only. Rows left behind by deleted
// projects (pre-cascade orphans) or held by archived projects would
// otherwise inflate the dashboard with work no scheduled run will drain.
// When the grove record can't be loaded the registry is unavailable, so
// fall back to the unrestricted count rather than report a false zero.
function serviceableProjectIds(
  groveId: string | null,
  mycoHome?: string,
): string[] | null {
  if (!groveId) return null;
  const home = mycoHome ?? resolveMycoHome();
  if (!loadGroveRecord(groveId, home)) return null;
  return listRegisteredProjects(groveId, home).map((project) => project.project_id);
}
