import { describe, expect, it } from "vitest";
import { unsafeOpaqueId } from "@awp/contracts";
import {
  renderApprovedLiveProject,
  renderApprovedLiveSystemSettings,
  type LiveHierarchy,
} from "../../apps/web/src/approved-live.js";

function emptyHierarchy(): LiveHierarchy {
  const projectId = unsafeOpaqueId("project:authoring");
  return {
    project: {
      id: projectId,
      name: "Authoring",
      repositoryUrl: "https://github.com/platform-modules/awp.git",
      requiredChecks: [],
      status: "active",
    } as never,
    vision: { id: "vision:1", sequence: 1, summary: "Existing canonical vision" },
    goals: [],
    plans: [],
    planRevisions: [],
    tasks: [],
    factoryRuns: [],
    agentRuns: [],
    attempts: [],
    workspaces: [],
    changeSets: [],
    reviews: [],
    verificationEvidence: [],
    reviewFindings: [],
    events: [],
  } as unknown as LiveHierarchy;
}

describe("approved live owner authoring", () => {
  it("keeps Overview information-first while exposing first-use mutation controls on canonical tabs", () => {
    const hierarchy = emptyHierarchy();
    const overview = renderApprovedLiveProject(hierarchy, "overview");
    expect(overview).toContain("New Project");
    expect(overview).not.toContain("Save ProjectVision");
    expect(overview).not.toContain("Create Goal");

    const vision = renderApprovedLiveProject(hierarchy, "vision");
    expect(vision).toContain("Save ProjectVision");
    expect(vision).toContain("Existing canonical vision");
    expect(vision).toContain('action="/internal/projects/project%3Aauthoring/vision"');

    const goals = renderApprovedLiveProject(hierarchy, "goals");
    expect(goals).toContain("Create Goal");
    expect(goals).toContain('name="successCriteria"');

    const plans = renderApprovedLiveProject(hierarchy, "plans");
    expect(plans).toContain("Real Planning");
    expect(plans).toContain("Plan authoring now starts in the Planning workspace.");
    expect(plans).toContain(
      `/projects/${encodeURIComponent(String(hierarchy.project.id))}/planning/new`,
    );
    expect(plans).not.toContain('name="taskTitles"');
    expect(plans).not.toContain('action="/internal/projects/project%3Aauthoring/plans"');
    expect(plans).toContain("No draft Plan is waiting to start");
  });
  it("renders durable journey stage history on the canonical Project surface", () => {
    const hierarchy = {
      ...emptyHierarchy(),
      events: [
        {
          id: "event:1",
          type: "TaskDispatched",
          occurredAt: "2026-08-24T09:00:00.000Z",
          aggregateType: "Task",
          aggregateId: "task:1",
          payload: {},
        },
        {
          id: "event:2",
          type: "MergeCompleted",
          occurredAt: "2026-08-24T09:00:05.000Z",
          aggregateType: "ChangeSet",
          aggregateId: "changeset:1",
          payload: {},
        },
      ],
    } satisfies LiveHierarchy;
    const html = renderApprovedLiveProject(hierarchy, "overview");
    expect(html).toContain("data-live-stage-timeline");
    expect(html).toContain('data-live-stage-event="TaskDispatched"');
    expect(html).toContain('data-event-aggregate-id="task:1"');
    expect(html).toContain("Task dispatched");
    expect(html).toContain('data-live-stage-event="MergeCompleted"');
    expect(html).toContain("Merge completed");
  });

  it("projects current I1 owner prerequisites into Needs Your Attention", () => {
    const base = emptyHierarchy();
    const projectId = base.project.id;
    const planId = unsafeOpaqueId("plan:attention");
    const planRevisionId = unsafeOpaqueId("plan-revision:attention");
    const hierarchy = {
      ...base,
      goals: [{ id: unsafeOpaqueId("goal:attention"), title: "Ship", status: "active" }],
      plans: [{ id: planId, title: "Ship I1", status: "draft" }],
      planRevisions: [
        {
          id: planRevisionId,
          planId,
          projectId,
          sequence: 1,
          title: "Ship I1",
          goalIds: [unsafeOpaqueId("goal:attention")],
        },
      ],
    } as unknown as LiveHierarchy;

    const withoutAccount = renderApprovedLiveProject(hierarchy, "overview", []);
    expect(withoutAccount).toContain("Needs Your Attention");
    expect(withoutAccount).toContain("Execution account required");
    expect(withoutAccount).toContain("Add account");
    expect(withoutAccount).not.toContain("Full Attention projection activates");

    const withAccount = renderApprovedLiveProject(hierarchy, "overview", [
      { accountKey: "owner-account", label: "Owner account", status: "available" } as never,
    ]);
    expect(withAccount).toContain("Approve &amp; start Ship I1");
    expect(withAccount).toContain("Review Plan");
  });
  it("renders authoritative Project Settings with editable overrides, provenance and locked deployment values", () => {
    const html = renderApprovedLiveProject(
      emptyHierarchy(),
      "settings",
      [
        {
          accountKey: "planner-account",
          label: "Planner account",
          providerKey: "codex",
          capabilities: ["provider.codex"],
          models: [
            {
              model: "gpt-5.6-luna",
              displayName: "GPT-5.6-Luna",
              description: "Fast and affordable agentic coding model.",
              defaultReasoningEffort: "medium",
              reasoningEfforts: [
                { effort: "low", description: "Fast" },
                { effort: "medium", description: "Balanced" },
                { effort: "high", description: "Deep" },
              ],
            },
          ],
        } as never,
      ],
      [
        {
          definition: {
            key: "execution.enabled",
            schemaVersion: 1,
            title: "Execution enabled",
            description: "Project execution off-switch for future FactoryRuns",
            defaultValue: true,
            allowedScopes: ["system", "project"],
            overrideStrategy: "replace",
            mutable: true,
            effectCategory: "future-runs-only",
            sensitiveReferenceOnly: false,
          },
          effective: {
            value: false,
            sourceScope: "project",
            sourceId: "project:authoring",
            provenanceChain: [{ scopeType: "project", scopeId: "project:authoring" }],
          },
        },
        {
          definition: {
            key: "execution.defaultModel",
            schemaVersion: 1,
            title: "Default execution model",
            description: "Default model for new FactoryRuns",
            allowedScopes: ["system", "project"],
            overrideStrategy: "replace",
            mutable: true,
            effectCategory: "future-runs-only",
            sensitiveReferenceOnly: false,
          },
          effective: {
            value: "gpt-5.6-luna",
            sourceScope: "system",
            sourceId: "system",
            provenanceChain: [{ scopeType: "system", scopeId: "system" }],
          },
        },
        {
          definition: {
            key: "planning.interviewerProviderId",
            schemaVersion: 1,
            title: "Planner provider",
            description: "Default provider for model-backed Planning interviews",
            allowedScopes: ["system", "project"],
            overrideStrategy: "replace",
            mutable: true,
            effectCategory: "future-planning-turns-only",
            sensitiveReferenceOnly: false,
          },
          effective: {
            value: "codex",
            sourceScope: "project",
            sourceId: "project:authoring",
            provenanceChain: [{ scopeType: "project", scopeId: "project:authoring" }],
          },
        },
        {
          definition: {
            key: "planning.interviewerAccountId",
            schemaVersion: 1,
            title: "Planner interviewer account",
            description: "Default account for model-backed Planning interviews",
            allowedScopes: ["system", "project"],
            overrideStrategy: "replace",
            mutable: true,
            effectCategory: "future-planning-turns-only",
            sensitiveReferenceOnly: true,
          },
          effective: {
            value: "planner-account",
            sourceScope: "project",
            sourceId: "project:authoring",
            provenanceChain: [{ scopeType: "project", scopeId: "project:authoring" }],
          },
        },
        {
          definition: {
            key: "planning.interviewerModel",
            schemaVersion: 1,
            title: "Planner interviewer model",
            description: "Default model for model-backed Planning interviews",
            allowedScopes: ["system", "project"],
            overrideStrategy: "replace",
            mutable: true,
            effectCategory: "future-planning-turns-only",
            sensitiveReferenceOnly: false,
          },
          effective: {
            value: "gpt-5.6-luna",
            sourceScope: "system",
            sourceId: "system",
            provenanceChain: [{ scopeType: "system", scopeId: "system" }],
          },
        },
        {
          definition: {
            key: "planning.interviewerReasoningEffort",
            schemaVersion: 1,
            title: "Planner reasoning effort",
            description: "Reasoning effort for model-backed Planning interviews",
            allowedScopes: ["system", "project"],
            overrideStrategy: "replace",
            mutable: true,
            effectCategory: "future-planning-turns-only",
            sensitiveReferenceOnly: false,
          },
          effective: {
            value: "high",
            sourceScope: "project",
            sourceId: "project:authoring",
            provenanceChain: [{ scopeType: "project", scopeId: "project:authoring" }],
          },
        },
        {
          definition: {
            key: "workspace.image",
            schemaVersion: 1,
            title: "Workspace image",
            description: "Deployment-managed OCI image used for I1 execution workspaces",
            defaultValue: "busybox:1.36.1",
            allowedScopes: ["system"],
            overrideStrategy: "replace",
            mutable: false,
            effectCategory: "restart/reload-required",
            sensitiveReferenceOnly: false,
          },
          effective: {
            value: `ghcr.io/platform-modules/awp-agent-runner@sha256:${"a".repeat(64)}`,
            sourceScope: "system",
            sourceId: "system",
            provenanceChain: [{ scopeType: "system", scopeId: "system" }],
          },
        },
      ],
    );

    expect(html).toContain("Project Settings");
    expect(html).toContain("One configuration authority");
    expect(html).toContain("data-project-config");
    expect(html).toContain('data-definition-key="execution.enabled"');
    expect(html).toContain("Reset to inherited");
    expect(html).toContain('data-definition-key="execution.defaultModel"');
    expect(html).toContain('id="planning-interviewer"');
    expect(html).toContain('data-definition-key="planning.interviewerProviderId"');
    expect(html).toContain('<option value="codex" selected>codex</option>');
    expect(html).toContain('data-definition-key="planning.interviewerProviderId"');
    expect(html).toContain('<option value="codex" selected>codex</option>');
    expect(html).toContain('data-definition-key="planning.interviewerAccountId"');
    expect(html).toContain('<option value="planner-account" selected>Planner account');
    expect(html).toContain('data-definition-key="planning.interviewerModel"');
    expect(html).toContain("GPT-5.6-Luna");
    expect(html).toContain('data-definition-key="planning.interviewerReasoningEffort"');
    expect(html).toContain("high — Deep");
    expect(html).toContain("future-planning-turns-only");
    expect(html).toContain("System · system");
    expect(html).toContain('data-config-definition="workspace.image"');
    expect(html).toContain("Read-only");
    expect(html).toContain("Deployment-managed for I1");
    expect(html).toContain("PostgreSQL");
    expect(html).not.toContain('data-definition-key="workspace.image"');
  });
  it("renders global System Settings with Planner defaults and Project inheritance navigation", () => {
    const settings = [
      {
        definition: {
          key: "planning.interviewerProviderId",
          schemaVersion: 1,
          title: "Planner provider",
          description: "Global Planner provider",
          allowedScopes: ["system", "project"],
          overrideStrategy: "replace",
          mutable: true,
          effectCategory: "future-planning-turns-only",
          sensitiveReferenceOnly: false,
        },
        effective: {
          value: "codex",
          sourceScope: "system",
          sourceId: "system",
          provenanceChain: [{ scopeType: "system", scopeId: "system" }],
        },
      },
      {
        definition: {
          key: "planning.interviewerAccountId",
          schemaVersion: 1,
          title: "Planner interviewer account",
          description: "Global Planner account",
          allowedScopes: ["system", "project"],
          overrideStrategy: "replace",
          mutable: true,
          effectCategory: "future-planning-turns-only",
          sensitiveReferenceOnly: true,
        },
        effective: {
          value: "planner-account",
          sourceScope: "system",
          sourceId: "system",
          provenanceChain: [{ scopeType: "system", scopeId: "system" }],
        },
      },
      {
        definition: {
          key: "planning.interviewerModel",
          schemaVersion: 1,
          title: "Planner interviewer model",
          description: "Global Planner model",
          allowedScopes: ["system", "project"],
          overrideStrategy: "replace",
          mutable: true,
          effectCategory: "future-planning-turns-only",
          sensitiveReferenceOnly: false,
        },
        effective: {
          value: "gpt-5.6-luna",
          sourceScope: "system",
          sourceId: "system",
          provenanceChain: [{ scopeType: "system", scopeId: "system" }],
        },
      },
      {
        definition: {
          key: "planning.interviewerReasoningEffort",
          schemaVersion: 1,
          title: "Planner reasoning effort",
          description: "Global Planner effort",
          allowedScopes: ["system", "project"],
          overrideStrategy: "replace",
          mutable: true,
          effectCategory: "future-planning-turns-only",
          sensitiveReferenceOnly: false,
        },
        effective: {
          value: "high",
          sourceScope: "system",
          sourceId: "system",
          provenanceChain: [{ scopeType: "system", scopeId: "system" }],
        },
      },
    ] as const;
    const html = renderApprovedLiveSystemSettings(
      [
        {
          id: "project:authoring",
          name: "Authoring",
          repositoryUrl: "https://github.com/platform-modules/awp.git",
          status: "active",
        },
      ],
      settings,
      [
        {
          accountKey: "planner-account",
          label: "Planner account",
          providerKey: "codex",
          capabilities: ["provider.codex"],
          models: [
            {
              model: "gpt-5.6-luna",
              displayName: "GPT-5.6-Luna",
              description: "Fast and affordable agentic coding model.",
              defaultReasoningEffort: "medium",
              reasoningEfforts: [
                { effort: "low", description: "Fast" },
                { effort: "medium", description: "Balanced" },
                { effort: "high", description: "Deep" },
              ],
            },
          ],
        } as never,
      ],
    );
    expect(html).toContain("System Settings");
    expect(html).toContain("Global defaults inherited by Projects");
    expect(html).toContain("data-system-config");
    expect(html).toContain('data-config-scope-type="system"');
    expect(html).toContain('data-config-scope-id="system"');
    expect(html).toContain('data-definition-key="planning.interviewerAccountId"');
    expect(html).toContain('<option value="planner-account" selected>Planner account');
    expect(html).toContain('data-definition-key="planning.interviewerModel"');
    expect(html).toContain("GPT-5.6-Luna");
    expect(html).toContain('data-definition-key="planning.interviewerReasoningEffort"');
    expect(html).toContain("high — Deep");
    expect(html).toContain("Clear global value");
    expect(html).toContain("/projects/project%3Aauthoring?tab=settings");
  });
});
