'use client';

import { DevopsPanel, type DevopsInfo } from '@bytelyst/devops/ui';

// Match the canonical token-access pattern used elsewhere in
// admin-web (settings/security, settings/devices, debug-sessions, …):
// the auth-context stores the access token under the
// `admin_access_token` key in localStorage. The createAuthProvider
// AuthContextValue does NOT expose a `getAccessToken` method, so the
// previous `const { getAccessToken } = useAuth()` would not type-check
// once @bytelyst/react-auth's public surface was tightened (see
// commit fixing devops page import 2026-05-23).
function getAccessToken(): string | null {
  if (typeof window === 'undefined') return null;
  return localStorage.getItem('admin_access_token');
}

const bundleStartTime = Date.now();

function humanizeUptime(seconds: number): string {
  if (seconds < 60) return `${seconds}s`;
  const mins = Math.floor(seconds / 60);
  if (mins < 60) return `${mins}m ${seconds % 60}s`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ${mins % 60}m`;
  const days = Math.floor(hrs / 24);
  return `${days}d ${hrs % 24}h ${mins % 60}m`;
}

export default function DevOpsPage() {
  async function fetchBackendInfo(): Promise<DevopsInfo> {
    const token = getAccessToken();
    const platformUrl = process.env.NEXT_PUBLIC_PLATFORM_URL || 'http://localhost:4003';
    const res = await fetch(`${platformUrl}/api/devops/info`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    if (!res.ok) {
      const body = (await res.json().catch(() => ({}))) as { error?: string };
      throw new Error(body?.error ?? `Backend devops info failed (${res.status})`);
    }
    return (await res.json()) as DevopsInfo;
  }

  async function fetchWebInfo(): Promise<DevopsInfo> {
    const env = process.env as Record<string, string | undefined>;
    const builtAt = env.NEXT_PUBLIC_BYTELYST_BUILT_AT || null;
    const startedAtMs = bundleStartTime;
    const uptimeSec = Math.floor((Date.now() - startedAtMs) / 1000);

    return {
      build: {
        commitSha: env.NEXT_PUBLIC_BYTELYST_COMMIT_SHA || null,
        commitShaFull: env.NEXT_PUBLIC_BYTELYST_COMMIT_SHA_FULL || null,
        branch: env.NEXT_PUBLIC_BYTELYST_BRANCH || null,
        builtAt,
        commitAuthor: env.NEXT_PUBLIC_BYTELYST_COMMIT_AUTHOR || null,
        commitMessage: env.NEXT_PUBLIC_BYTELYST_COMMIT_MESSAGE || null,
        dockerImage: env.NEXT_PUBLIC_BYTELYST_DOCKER_IMAGE || null,
      },
      runtime: {
        uptimeSeconds: uptimeSec,
        uptimeHuman: humanizeUptime(uptimeSec),
        nodeVersion: 'browser',
        platform: typeof window !== 'undefined' ? navigator.platform || 'unknown' : 'unknown',
        arch: typeof window !== 'undefined' && navigator.userAgent.includes('arm') ? 'arm' : 'x86',
        pid: 0,
        hostname: typeof window !== 'undefined' ? window.location.hostname : 'unknown',
        memoryMb: Math.round(
          ((performance as unknown as { memory?: { usedJSHeapSize?: number } })?.memory
            ?.usedJSHeapSize ?? 0) /
            1024 /
            1024
        ),
        heapMb: Math.round(
          ((performance as unknown as { memory?: { usedJSHeapSize?: number } })?.memory
            ?.usedJSHeapSize ?? 0) /
            1024 /
            1024
        ),
        startedAt: new Date(startedAtMs).toISOString(),
      },
      config: {
        productId: env.NEXT_PUBLIC_PRODUCT_ID || 'admin',
        serviceName: 'admin-web',
        serviceVersion: '1.0.0',
        nodeEnv: env.NODE_ENV || 'production',
        envKeys: Object.keys(env)
          .filter(k => /^NEXT_PUBLIC_/.test(k) && !/SECRET|KEY|TOKEN|PASSWORD/i.test(k))
          .sort(),
      },
      extra: {
        platformUrl: env.NEXT_PUBLIC_PLATFORM_URL || 'http://localhost:4003',
        userAgent: typeof window !== 'undefined' ? navigator.userAgent : 'unknown',
      },
    };
  }

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900">DevOps</h1>
        <p className="text-sm text-gray-600">System information and deployment details</p>
      </div>
      <DevopsPanel fetchInfo={fetchBackendInfo} fetchWebInfo={fetchWebInfo} />
    </div>
  );
}
