import https from "node:https";
import fs from "node:fs";
import { getAuthenticatedUser } from "@/auth";
import { AgentSettingsForm } from "@/components/settings/AgentSettingsForm";
import type { AgentConfig } from "@gsc/chat";

const OPS_API_URL = process.env.OPS_API_URL || "https://172.17.8.20:8443";
const OPS_API_KEY = process.env.OPS_API_KEY || "";

let _tlsAgent: https.Agent | null = null;
function getTlsAgent(): https.Agent {
  if (!_tlsAgent) {
    _tlsAgent = new https.Agent({
      cert: fs.readFileSync("/etc/mcp-certs/client.crt"),
      key: fs.readFileSync("/etc/mcp-certs/client.key"),
      ca: fs.readFileSync("/etc/mcp-certs/ca-chain.crt"),
      rejectUnauthorized: false,
    });
  }
  return _tlsAgent;
}

function opsApiGet(path: string): Promise<string> {
  const url = new URL(`${OPS_API_URL}${path}`);
  return new Promise((resolve, reject) => {
    const req = https.request(
      {
        hostname: url.hostname,
        port: url.port,
        path: url.pathname + url.search,
        method: "GET",
        agent: getTlsAgent(),
        headers: {
          "X-API-Key": OPS_API_KEY,
          "Content-Type": "application/json",
        },
      },
      (res) => {
        const chunks: Buffer[] = [];
        res.on("data", (chunk) => chunks.push(chunk));
        res.on("end", () => {
          const body = Buffer.concat(chunks).toString();
          if (res.statusCode && res.statusCode >= 400) {
            reject(new Error(`HTTP ${res.statusCode}`));
          } else {
            resolve(body);
          }
        });
      }
    );
    req.on("error", reject);
    req.end();
  });
}

async function getAgentConfig(userId?: string, tenantId?: string): Promise<AgentConfig> {
  if (!userId || !tenantId || !OPS_API_KEY) {
    return defaultConfig();
  }

  try {
    const data = await opsApiGet(
      `/api/v1/agents/me?userId=${userId}&tenantId=${tenantId}`
    );
    const envelope = JSON.parse(data);
    if (envelope.data?.config) {
      return envelope.data.config as AgentConfig;
    }
  } catch {
    // Fall through to default
  }

  return defaultConfig();
}

function defaultConfig(): AgentConfig {
  return {
    id: "default",
    userId: "",
    agentName: "",
    userName: "",
    activePersonaId: "default",
    personas: [
      {
        id: "default",
        name: "Default Assistant",
        archetype: "Balanced",
        voiceTone: "Professional",
        mbti: "INTJ",
        personality: {
          openness: 50,
          conscientiousness: 50,
          extraversion: 50,
          agreeableness: 50,
          neuroticism: 50,
        },
        positiveRules: [
          "Be helpful and concise",
          "Provide accurate information",
          "Respect user privacy",
        ],
        negativeRules: [
          "Do not share personal data",
          "Do not make assumptions about intent",
        ],
        backstory: "",
        worldBuilding: "",
        topicalRails: [],
        defaultModel: "claude-3-5-sonnet",
        temperature: 0.7,
        maxTokensPerTurn: 2048,
        guardrailsConfig: {
          maxResponseLength: 4000,
          allowCodeExecution: false,
          allowExternalLinks: true,
        },
        status: "active",
      },
    ],
    memorySettings: {
      retentionDays: 30,
    },
  };
}

export default async function AgentSettingsPage() {
  const user = await getAuthenticatedUser();
  const config = await getAgentConfig(user?.gscUserId, user?.tenantId);

  return (
    <AgentSettingsForm initialConfig={config} userGivenName={user?.givenName || ""} />
  );
}
