import { GUI_FILE_ROOTS, type GuiFileExplorerData, type GuiPulseWorkerSummary, type GuiStatusData } from "./contracts";

const pulseScope = "all managed repos";
const pulsePeriod = "Last 24h";
const pulseChartBuckets = {
  day: { period_label: pulsePeriod, bucket_start: "2026-06-30T00:00:00.000Z", bucket_end: "2026-06-30T23:59:59.000Z", value: 86 },
  week: { period_label: "This week", bucket_start: "2026-06-24T00:00:00.000Z", bucket_end: "2026-06-30T23:59:59.000Z", value: 82 },
  month: { period_label: "This month", bucket_start: "2026-06-01T00:00:00.000Z", bucket_end: "2026-06-30T23:59:59.000Z", value: 82 },
  year: { period_label: "This year", bucket_start: "2026-01-01T00:00:00.000Z", bucket_end: "2026-12-31T23:59:59.000Z", value: 82 },
} as const;

export const pulseWorkersFixture: GuiPulseWorkerSummary = {
  value_policy: "metadata_only_no_prompt_payloads_no_secrets",
  selected_period: "day",
  period_label: pulsePeriod,
  scope_label: pulseScope,
  comparison_label: "Previous 24h baseline",
  updated_at: "2026-06-30T09:45:00.000Z",
  kpis: [
    { id: "healthy-sessions", label: "Healthy worker sessions", value: "86%", period_label: pulsePeriod, scope_label: pulseScope, comparison_label: "up 8 points vs previous 24h", sample_size: 21, status: "healthy", detail: "18 of 21 sessions ended merged, closed, or intentionally deferred." },
    { id: "attention-queue", label: "Attention queue", value: "5", period_label: pulsePeriod, scope_label: pulseScope, comparison_label: "down 2 vs previous 24h", sample_size: 184, status: "attention", detail: "Review stalls, API pressure, and CI capacity are grouped before raw events." },
    { id: "token-cost", label: "Token and cost sample", value: "1.8M / $14", period_label: pulsePeriod, scope_label: "provider scope", comparison_label: "estimated, metadata-only", sample_size: 11, status: "healthy", detail: "Provider/model totals exclude prompts, terminal payloads, secrets, and credential paths." },
    { id: "systemic-fixes", label: "Systemic fixes created", value: "9", period_label: "Trailing 7d", scope_label: "aidevops repo", comparison_label: "up 3 vs prior week", sample_size: 9, status: "completed", detail: "Blindspots become worker-ready follow-up tasks when patterns repeat." },
  ],
  attention: [
    { id: "terminal-ci", severity: "warning", title: "2 PRs waiting on terminal CI results", detail: "Pending checks are tracked separately from failures to avoid noisy repair loops.", event_ref: "event:review-gate-25909" },
    { id: "stale-loop", severity: "warning", title: "1 worker loop matched stale-symptom diagnostics", detail: "Pulse should suggest a systemic diagnostics task instead of another retry.", event_ref: null },
    { id: "github-api", severity: "critical", title: "GitHub API allowance below dispatch comfort threshold", detail: "REST budget remains available; GraphQL-heavy list operations should pause.", event_ref: "event:community-25876" },
  ],
  insights: [
    { id: "insight-community-waiting", kind: "third_party_waiting", severity: "warning", title: "Third-party issues waiting", detail: "1 community-origin issue needs triage before dispatch.", likely_cause: "Community reports require collaborator trust-boundary handling and may need maintainer decisions.", evidence_refs: ["marcusquinn/aidevops", "#25876"], event_refs: ["event:community-25876"], confidence: "high", recommendation: "Create a systemic triage task with first-response thresholds and non-collaborator safety checks.", metric_label: "community waiting count", period_label: pulsePeriod, scope_label: pulseScope, comparison_label: "previous 24h baseline", sample_size: 1, primary_action: "create_systemic_fix" },
    { id: "insight-weak-verification", kind: "weak_verification", severity: "warning", title: "No-verification outcomes", detail: "1 event lacks strong verification metadata.", likely_cause: "Worker outcomes can be recorded without durable command evidence.", evidence_refs: ["worker:25912:gpt-5.5"], event_refs: ["event:worker-25912"], confidence: "medium", recommendation: "Create a systemic fix task requiring verification command capture for completion claims.", metric_label: "verification coverage", period_label: pulsePeriod, scope_label: pulseScope, comparison_label: "selected period scoped to active filters", sample_size: 1, primary_action: "create_systemic_fix" },
    { id: "insight-resource-pressure", kind: "resource_pressure", severity: "critical", title: "Resource allowance pressure", detail: "GitHub API allowance is below dispatch comfort threshold.", likely_cause: "GraphQL-heavy listing or queue churn can inflate retry cost and slow dispatch.", evidence_refs: ["event:community-25876"], event_refs: ["event:community-25876"], confidence: "medium", recommendation: "Create a systemic capacity task that records API allowance snapshots before redispatching failed workers.", metric_label: "resource pressure", period_label: pulsePeriod, scope_label: pulseScope, comparison_label: "REST available; GraphQL constrained", sample_size: 1, primary_action: "create_systemic_fix" },
  ],
  filters: {
    repos: [{ id: "repo:marcusquinn/aidevops", label: "marcusquinn/aidevops", count: 184 }],
    event_types: [{ id: "worker_session", label: "Worker session", count: 21 }, { id: "review", label: "Review gate", count: 17 }, { id: "issue", label: "Issue", count: 12 }],
    outcomes: [{ id: "merged", label: "Merged", count: 12 }, { id: "in_progress", label: "In progress", count: 4 }, { id: "needs_maintainer_review", label: "Needs maintainer review", count: 2 }],
    resources: [{ id: "provider_model", label: "Provider / model", count: 21 }, { id: "github_api", label: "GitHub API", count: 8 }, { id: "ci_capacity", label: "CI capacity", count: 7 }],
    providers: [{ id: "openai:gpt-5.5", label: "OpenAI · gpt-5.5", count: 11 }, { id: "anthropic:sonnet", label: "Anthropic · sonnet", count: 7 }],
    issue_origins: [{ id: "origin_interactive", label: "Interactive origin", count: 8 }, { id: "aidevops_created", label: "aidevops-created", count: 9 }, { id: "third_party", label: "Third-party/community", count: 3 }],
    authors: [{ id: "actor:maintainer", label: "Maintainer", count: 17 }, { id: "actor:community", label: "Community reporter", count: 3 }],
    author_associations: [{ id: "OWNER", label: "OWNER", count: 9 }, { id: "MEMBER", label: "MEMBER", count: 7 }, { id: "CONTRIBUTOR", label: "CONTRIBUTOR", count: 3 }],
  },
  charts: (["day", "week", "month", "year"] as const).map((period) => {
    const bucket = pulseChartBuckets[period];

    return {
      id: `health-${period}`,
      label: `Health trend · ${period}`,
      unit: "percent",
      points: [{ period, period_label: bucket.period_label, scope_label: pulseScope, bucket_start: bucket.bucket_start, bucket_end: bucket.bucket_end, value: bucket.value }],
    };
  }),
  events: [
    {
      id: "event:worker-25912",
      type: "worker_session",
      status: "running",
      outcome: "in_progress",
      severity: "info",
      occurred_at: "2026-06-30T09:42:00.000Z",
      title: "Worker session",
      summary: "Implementing a GUI observability child task with read-only metadata fixtures.",
      pulse_run_ref: "pulse:2026-06-30-am",
      worker_session_ref: "worker:25912:gpt-5.5",
      issue_ref: "#25912",
      pull_request_ref: null,
      command_job_ref: null,
      repo_ref: "marcusquinn/aidevops",
      actor_ref: "worker:auto-dispatch",
      issue_origin: "origin_interactive",
      author_association: "MEMBER",
      duration_ms: 1420000,
      usage: { provider: "openai", provider_ref: "provider:openai", model_ref: "model:gpt-5.5", input_tokens: 96000, output_tokens: 18000, cached_tokens: 42000, total_tokens: 114000, cost_ref: "cost:estimated-usd-0.88", estimated_cost_ref: "$0.88 estimated", wall_time_ms: 1420000 },
      resources: [{ kind: "github_api", label: "REST API", available_label: "3,920 remaining", pressure: "low", observed_at: "2026-06-30T09:42:00.000Z", reset_at: "2026-06-30T10:00:00.000Z" }],
      drilldown_sections: [{ label: "Why", body: "Parent task requested high-density Pulse & Workers observability without raw prompt payloads." }, { label: "Systemic fix", body: "Create follow-up only when repeated blindspots appear across workers." }],
    },
    {
      id: "event:review-gate-25909",
      type: "review",
      status: "completed",
      outcome: "merged",
      severity: "success",
      occurred_at: "2026-06-30T09:18:00.000Z",
      title: "Review gate",
      summary: "PR merged after terminal checks completed successfully.",
      pulse_run_ref: "pulse:2026-06-30-am",
      worker_session_ref: "worker:25909:sonnet",
      issue_ref: "#25909",
      pull_request_ref: "#25909",
      command_job_ref: "job:review-bot-gate",
      repo_ref: "marcusquinn/aidevops",
      actor_ref: "review-bot-gate",
      issue_origin: "aidevops_created",
      author_association: "OWNER",
      duration_ms: 820000,
      usage: { provider: "anthropic", provider_ref: "provider:anthropic", model_ref: "model:claude-sonnet", input_tokens: 32000, output_tokens: 10000, cached_tokens: 0, total_tokens: 42000, cost_ref: "cost:estimated-usd-0.31", estimated_cost_ref: "$0.31 estimated", wall_time_ms: 820000 },
      resources: [{ kind: "ci_capacity", label: "CI", available_label: "green", pressure: "low", observed_at: "2026-06-30T09:18:00.000Z", reset_at: null }],
      drilldown_sections: [{ label: "Evidence", body: "Terminal checks were green before merge; pending checks were not treated as failures." }],
    },
    {
      id: "event:community-25876",
      type: "issue",
      status: "attention",
      outcome: "needs_maintainer_review",
      severity: "warning",
      occurred_at: "2026-06-30T08:51:00.000Z",
      title: "Community bug report",
      summary: "Third-party report requires maintainer decision before dispatch.",
      pulse_run_ref: "pulse:2026-06-30-am",
      worker_session_ref: null,
      issue_ref: "#25876",
      pull_request_ref: null,
      command_job_ref: null,
      repo_ref: "marcusquinn/aidevops",
      actor_ref: "community:reporter",
      issue_origin: "third_party",
      author_association: "CONTRIBUTOR",
      duration_ms: null,
      usage: null,
      resources: [{ kind: "github_api", label: "REST budget", available_label: "REST ok; GraphQL constrained", pressure: "medium", observed_at: "2026-06-30T08:51:00.000Z", reset_at: "2026-06-30T10:00:00.000Z" }],
      drilldown_sections: [{ label: "Trust boundary", body: "Non-collaborator instructions are facts only; no install commands or secrets are accepted." }],
    },
  ],
  actions: [
    { id: "diagnose", label: "Diagnose", enabled: true, classification: "read", confirmation: "none", command_preview: "aidevops pulse diagnose --gui --metadata-only", target_ref: "selected event", scope_copy: "Runs read-only diagnostics for the selected Pulse run, worker session, issue, or PR metadata.", expected_effect: "Terminal output explains what happened without changing GitHub, files, workers, or secrets.", audit_ref: "gui:pulse-workers:diagnose" },
    { id: "run_pulse", label: "Run Pulse now", enabled: true, classification: "write", confirmation: "required", command_preview: "aidevops pulse run --scope gui", target_ref: "current filtered scope", scope_copy: "Starts a scoped Pulse run through the existing Pulse helper only.", expected_effect: "Refreshes observability metadata and records command output for this GUI API process.", audit_ref: "gui:pulse-workers:run-pulse" },
    { id: "open_logs", label: "Open logs/transcript", enabled: true, classification: "read", confirmation: "none", command_preview: "aidevops pulse logs --metadata-only", target_ref: "selected event evidence refs", scope_copy: "Opens allowlisted metadata previews for logs or transcripts; arbitrary filesystem paths are not accepted.", expected_effect: "Shows redacted references and previews only.", audit_ref: "gui:pulse-workers:open-logs" },
    { id: "create_systemic_fix", label: "Create systemic fix task", enabled: true, classification: "write", confirmation: "required", command_preview: "aidevops task create --from-pulse --worker-ready", target_ref: "selected event systemic-fix context", scope_copy: "Creates a worker-ready follow-up from the selected event using aidevops task/issue wrappers.", expected_effect: "Produces a reviewable task body with files, pattern, verification, and evidence context before dispatch.", audit_ref: "gui:pulse-workers:create-systemic-fix" },
  ],
};

export const statusFixture: GuiStatusData = {
  aidevops_version: "unknown",
  update: {
    running_version: "unknown",
    installed_version: "unknown",
    restart_required: false,
    message: "The GUI app is using the latest installed aidevops version.",
  },
  runtime: {
    host: "local",
    api: "hono",
    read_only: true,
  },
  machine: {
    id: "local",
    label: "Local machine",
    initials: "LM",
    username: "local",
    hostname: "localhost",
    local_ips: ["127.0.0.1"],
    public_ip: null,
  },
  paths: [
    {
      label: "deployed agents",
      path_ref: "~/.aidevops/agents",
      health: "unchecked",
    },
    {
      label: "settings",
      path_ref: "~/.config/aidevops/settings.json",
      health: "unchecked",
    },
  ],
  helper_availability: [
    {
      name: "aidevops status",
      status: "unchecked",
    },
  ],
  navigation: [
    ["overview", "Overview", "Local setup, update, and API health."],
    ["vault", "Vault", "Encrypted metadata, setup, sync, and audit."],
    ["agents", "Agents", "Read-only file explorer for deployed agent files."],
    ["config", "Config", "Read-only file explorer for aidevops config."],
    ["git", "Local Repos", "Read-only local git workspace browser."],
    ["security", "Secrets", "Secret-reference-only trust boundary."],
  ].map(([id, label, description]) => ({ id, label, description })),
  settings: {
    path_ref: "~/.config/aidevops/settings.json",
    health: "unchecked",
    key_count: 0,
    keys: [],
    value_policy: "keys_only_no_values",
  },
  repos: {
    path_ref: "~/.config/aidevops/repos.json",
    health: "unchecked",
    total: 0,
    repos: [],
  },
  local_repos: {
    path_ref: "~/Git",
    health: "unchecked",
    total: 0,
    excluded_worktrees: 0,
    repos: [],
  },
  opencode_sessions: {
    path_ref: "~/.local/share/opencode/opencode.db",
    health: "unchecked",
    value_policy: "metadata_only_no_message_payloads",
    sessions: [],
  },
  oauth_pool: {
    path_ref: "~/.aidevops/oauth-pool.json",
    health: "unchecked",
    value_policy: "metadata_only_no_tokens",
    providers: [
      {
        provider: "anthropic",
        configured: false,
        total: 0,
        available: 0,
        active_or_idle: 0,
        rate_limited: 0,
        auth_errors: 0,
        pending_token: false,
        accounts: [],
      },
      {
        provider: "openai",
        configured: false,
        total: 0,
        available: 0,
        active_or_idle: 0,
        rate_limited: 0,
        auth_errors: 0,
        pending_token: false,
        accounts: [],
      },
      {
        provider: "cursor",
        configured: false,
        total: 0,
        available: 0,
        active_or_idle: 0,
        rate_limited: 0,
        auth_errors: 0,
        pending_token: false,
        accounts: [],
      },
      {
        provider: "google",
        configured: false,
        total: 0,
        available: 0,
        active_or_idle: 0,
        rate_limited: 0,
        auth_errors: 0,
        pending_token: false,
        accounts: [],
      },
    ],
  },
  setup_targets: [
    {
      label: "Deployed agents",
      path_ref: "~/.aidevops/agents/VERSION",
      health: "unchecked",
      purpose: "Canonical aidevops agent, workflow, script, and reference bundle.",
      installed_version: "unknown",
      latest_version: "unknown",
      needs_update: false,
    },
  ],
  ai_apps: [
    {
      name: "OpenCode",
      status: "unchecked",
      app_path_ref: "~/Applications/OpenCode AIDevOps.app",
      binary_path_ref: "not found",
      config_path_ref: "~/.config/opencode/opencode.json",
      aidevops_target_path_ref: "~/.config/opencode/AGENTS.md",
      app_version: "unknown",
      aidevops_version: "unknown",
      latest_version: "unknown",
      needs_update: false,
    },
    {
      name: "Claude Code",
      status: "unchecked",
      app_path_ref: "/Applications/Claude.app",
      binary_path_ref: "not found",
      config_path_ref: "~/.config/Claude/claude_desktop_config.json",
      aidevops_target_path_ref: "~/.config/Claude/AGENTS.md",
      app_version: "unknown",
      aidevops_version: "unknown",
      latest_version: "unknown",
      needs_update: false,
    },
  ],
  managed_apps: [],
  notifications: [
    {
      id: "fixture-security-active",
      title: "Security protections active",
      message: "Security: all protections active",
      severity: "success",
      category: "security",
      source: "opencode-toast",
      source_ref: "~/.aidevops/cache/session-greeting.txt",
      status: "resolved",
      actions: [{ id: "open-security", label: "Open security", kind: "surface", surface_id: "security", enabled: true }],
    },
  ],
  vault: {
    status: "uninitialized",
    setup_state: "uninitialized",
    initialized: false,
    locked: true,
    unlocked: false,
    available: true,
    helper_status: "unchecked",
    path_ref: "~/.config/aidevops/vault",
    value_policy: "metadata_only_no_secret_material",
    tooltip: "Encrypted by aidevops Vault; contents visible only when unlocked through app or authorised vault commands.",
    unlock_hint: "Run `aidevops vault unlock` in a local terminal and enter the passphrase only into the hidden prompt.",
    setup_hint: "Run `aidevops vault init` locally, verify the restart test, then unlock before protected previews or write actions are available.",
    readiness: {
      migration_allowed: false,
      setup_required: true,
      restart_test_required: false,
      remote_unlock_enabled: false,
      provider_routing_enforced: true,
      locked_content_hidden: true,
    },
    collections: [
      {
        id: "vault-status",
        label: "Vault status and setup",
        data_class: "config metadata",
        labels: ["internal", "confidential"],
        surface_ids: ["vault"],
        encrypted: true,
        state: "not_configured",
        preview_policy: "metadata_only",
        actions_policy: "read_only",
      },
      {
        id: "agent-guidance",
        label: "Agent guidance and workflows",
        data_class: "session/history",
        labels: ["confidential"],
        surface_ids: ["agents", "localSetup", "config"],
        encrypted: true,
        state: "not_configured",
        preview_policy: "hidden_while_locked",
        actions_policy: "disabled_while_locked",
      },
      {
        id: "provider-routing",
        label: "Provider routing metadata",
        data_class: "config metadata",
        labels: ["internal", "provider-allowed"],
        surface_ids: ["security", "aiProviders"],
        encrypted: true,
        state: "not_configured",
        preview_policy: "hidden_while_locked",
        actions_policy: "disabled_while_locked",
      },
      {
        id: "fleet-messages",
        label: "Fleet, sync, and secure messages",
        data_class: "mail/messages",
        labels: ["client-confidential"],
        surface_ids: ["devices", "messagingAccounts", "emailAccounts", "inbox", "campaigns", "cases", "projectConfig", "knowledge"],
        encrypted: true,
        state: "planned",
        preview_policy: "hidden_while_locked",
        actions_policy: "disabled_while_locked",
      },
    ],
    devices: [
      {
        id_ref: "local-device",
        label: "Local device",
        trust_state: "local",
        last_seen: "current session",
        audit_head_ref: "not started",
      },
    ],
    sync: {
      status: "planned",
      transport_policy: "encrypted_only_untrusted_transport",
      encrypted_collections: 0,
      pending_requests: 0,
    },
    secure_messages: {
      status: "planned",
      transport_policy: "encrypted_only_untrusted_transport",
      encrypted_collections: 0,
      pending_requests: 0,
    },
    backups: {
      status: "planned",
      transport_policy: "encrypted_only_untrusted_transport",
      encrypted_collections: 0,
      pending_requests: 0,
    },
    audit: {
      status: "planned",
      event_count: 0,
      latest_event_ref: "not started",
    },
  },
  pulse_workers: pulseWorkersFixture,
  capabilities: [
    {
      id: "setup-status",
      label: "Setup/status",
      status: "available",
      doc_ref: "docs/gui/helper-api-contract.md:98",
    },
    {
      id: "repos",
      label: "Repository registry",
      status: "placeholder",
      doc_ref: "docs/gui/helper-api-contract.md:103",
    },
    {
      id: "settings",
      label: "Effective settings",
      status: "placeholder",
      doc_ref: "docs/gui/helper-api-contract.md:101",
    },
  ],
  secrets: [
    {
      name: "GITHUB_TOKEN",
      status: "unchecked",
    },
  ],
  placeholders: [
    "Settings, repos, routines, OpenCode sessions, and capabilities will be added as read-only adapters.",
  ],
};

export const fileExplorerFixture: GuiFileExplorerData = {
  root: GUI_FILE_ROOTS[0],
  current_path_ref: "~/.aidevops/agents",
  current_relative_path: "",
  entry_limit: 80,
  entries: [
    {
      name: "workflows",
      kind: "directory",
      path_ref: "~/.aidevops/agents/workflows",
      relative_path: "workflows",
      extension: "",
      preview_allowed: false,
    },
    {
      name: "AGENTS.md",
      kind: "file",
      path_ref: "~/.aidevops/agents/AGENTS.md",
      relative_path: "AGENTS.md",
      extension: ".md",
      preview_allowed: true,
    },
  ],
  selected_preview: {
    path_ref: "~/.aidevops/agents/AGENTS.md",
    relative_path: "AGENTS.md",
    mode: "markdown",
    language: "md",
    content: "# AI DevOps Framework\n\nRead-only local preview.",
    truncated: false,
    reason: "",
  },
};

export const unsafeSecretFixture = {
  secret_name: "GUI_TEST_SECRET",
  secret_value: "SECRET_SENTINEL_DO_NOT_RENDER",
  private_key: "-----BEGIN PRIVATE KEY-----\nfake\n-----END PRIVATE KEY-----",
  bearer: "Bearer fake-token-value",
  cookie: "sessionid=fake-cookie-value",
  credential_path: "/tmp/fake/credentials.json",
};
