import { NextRequest, NextResponse } from "next/server";
import OpenAI from "openai";
import { logger } from "@/lib/logger";
import { guessCompanyDomain } from "@/lib/company-utils";
import { checkRateLimit, getClientIP, createRateLimitResponse } from "@/lib/rate-limit";

// Rate limit: 5 research requests per 10 minutes (OpenAI costs money)
const RESEARCH_RATE_LIMIT = 5;
const RESEARCH_WINDOW_MS = 10 * 60 * 1000;

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

interface ResearchRequest {
  companyName: string;
  abn: string;
  state: string;
  postcode: string;
  entityType: string;
  gstRegistered: boolean;
  website?: string;
}

interface CompanyResearch {
  description: string;
  services: string[];
  estimatedSize: string;
  website: string | null;
  industry: string;
}

/**
 * POST /api/ai/research-company
 * 
 * Takes ABN lookup data, tries to find the company website,
 * and uses AI to generate a useful company profile summary.
 */
export async function POST(request: NextRequest) {
  try {
    const clientIP = getClientIP(request);
    const rateLimit = await checkRateLimit(`research:${clientIP}`, RESEARCH_RATE_LIMIT, RESEARCH_WINDOW_MS);
    if (!rateLimit.allowed) {
      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
      return createRateLimitResponse(clientIP, retryAfter);
    }

    const body: ResearchRequest = await request.json();
    const { companyName, abn, state, postcode, entityType, gstRegistered, website } = body;

    if (!companyName || !abn) {
      return NextResponse.json({ error: "Missing companyName or abn" }, { status: 400 });
    }

    // Step 1: Try to discover the company website
    let discoveredWebsite = website || null;
    let websiteContent = "";

    if (!discoveredWebsite) {
      const possibleDomains = guessCompanyDomain(companyName);
      const cleanedCompany = companyName
        .toLowerCase()
        .replace(/\b(?:pty|ltd|limited|inc|incorporated|corp|corporation|co|company|services?)\b/g, "")
        .replace(/[^a-z0-9\s]/g, " ")
        .replace(/\s+/g, " ")
        .trim();
      const companyTokens = cleanedCompany.split(" ").filter((t) => t.length >= 3);

      for (const domain of possibleDomains) {
        try {
          // Guard: reject clearly unrelated short domains (e.g. lf.net)
          const host = domain.split(".")[0] || "";
          const tokenMatch = companyTokens.some((t) => host.includes(t) || t.includes(host));
          if (!tokenMatch) continue;

          const res = await fetch(`https://${domain}`, {
            method: "HEAD",
            signal: AbortSignal.timeout(3000),
            redirect: "follow",
          });
          if (res.ok) {
            discoveredWebsite = `https://${domain}`;
            break;
          }
        } catch {
          // Domain doesn't exist, try next
        }
      }
    }

    // Step 2: Try to fetch website content for better research
    if (discoveredWebsite) {
      try {
        const res = await fetch(discoveredWebsite, {
          signal: AbortSignal.timeout(5000),
          headers: { "User-Agent": "RateRight/1.0 (company-research)" },
        });
        if (res.ok) {
          const html = await res.text();
          // Extract text content (strip tags, limit to 2000 chars)
          websiteContent = html
            .replace(/<script[\s\S]*?<\/script>/gi, "")
            .replace(/<style[\s\S]*?<\/style>/gi, "")
            .replace(/<[^>]+>/g, " ")
            .replace(/\s+/g, " ")
            .trim()
            .slice(0, 2000);
        }
      } catch {
        // Couldn't fetch, continue without
      }
    }

    // Step 3: Use AI to generate company profile
    const prompt = buildResearchPrompt(companyName, abn, state, postcode, entityType, gstRegistered, websiteContent);

    const completion = await openai.chat.completions.create({
      model: "gpt-4o-mini",
      temperature: 0.3,
      max_tokens: 500,
      messages: [
        {
          role: "system",
          content: "You are a business research assistant. Given information about an Australian construction company, generate a concise company profile. Return ONLY valid JSON, no markdown."
        },
        { role: "user", content: prompt }
      ],
    });

    const aiText = completion.choices[0]?.message?.content?.trim() || "{}";
    
    let research: CompanyResearch;
    try {
      // Strip markdown code blocks if present
      const cleaned = aiText.replace(/^```json?\s*\n?/i, "").replace(/\n?```\s*$/i, "");
      research = JSON.parse(cleaned);
    } catch {
      logger.error("[Research] Failed to parse AI response:", aiText);
      research = {
        description: `${companyName} is a construction company based in ${state}.`,
        services: ["Construction"],
        estimatedSize: entityType === "Individual/Sole Trader" ? "1-5" : "Unknown",
        website: discoveredWebsite,
        industry: "Construction",
      };
    }

    // Ensure website is populated
    if (!research.website && discoveredWebsite) {
      research.website = discoveredWebsite;
    }

    return NextResponse.json({
      success: true,
      data: research,
    });
  } catch (err) {
    logger.error("[Research] Error:", err);
    return NextResponse.json({ error: "Research failed" }, { status: 500 });
  }
}

function buildResearchPrompt(
  name: string,
  abn: string,
  state: string,
  postcode: string,
  entityType: string,
  gstRegistered: boolean,
  websiteContent: string
): string {
  let prompt = `Research this Australian construction company and generate a profile:

Company: ${name}
ABN: ${abn}
State: ${state}
Postcode: ${postcode}
Entity Type: ${entityType}
GST Registered: ${gstRegistered ? "Yes" : "No"}`;

  if (websiteContent) {
    prompt += `\n\nWebsite content (excerpt):\n${websiteContent}`;
  }

  prompt += `\n\nReturn JSON with these fields:
{
  "description": "2-3 sentence description of what the company does",
  "services": ["list", "of", "construction", "services"],
  "estimatedSize": "employee count estimate: 1-5, 5-20, 20-50, 50-200, 200+",
  "website": "company website URL if found, or null",
  "industry": "specific industry like 'Commercial Construction', 'Residential Building', 'Civil Engineering', etc."
}

Base your answer on the company name, entity type, and any website content. For construction companies without website content, make reasonable assumptions based on the company name and Australian construction industry.`;

  return prompt;
}
