import { getNaicsForIndustry, parseStateCode } from "@/lib/sam-gov/naics-map";
import { describeNaics, getMarketStatsForNaics } from "@/lib/federal-work/naics-labels";
import type { Business } from "@/lib/types";

export interface FederalWorkStep {
  id: string;
  title: string;
  summary: string;
  detail: string;
  /** External link (SAM.gov, USAspending, etc.) */
  href?: string;
  hrefLabel?: string;
  /** Step is auto-completed when this condition is met in the app */
  autoComplete?: "has_federal_opportunities" | "viewed_naics";
}

export const FEDERAL_WORK_STEPS: FederalWorkStep[] = [
  {
    id: "understand",
    title: "Learn that federal work exists for your trade",
    summary: "The government buys landscaping, plumbing, HVAC, cleaning, IT, and more — often in $10K–$250K chunks near you.",
    detail:
      "Every year federal agencies award thousands of contracts to small businesses. You do not need to be a defense giant. Many jobs are grounds maintenance at a base, HVAC at a VA clinic, or plumbing at a federal building — work you already know how to do.",
  },
  {
    id: "register",
    title: "Register free in SAM.gov (get your UEI)",
    summary: "Required before you can be paid on any federal contract. Registration is free and takes about 1–2 hours.",
    detail:
      "SAM.gov is the official vendor database. You will receive a Unique Entity ID (UEI). Without this, agencies cannot award you a contract. Gather your EIN, bank info, and NAICS codes before starting.",
    href: "https://sam.gov/content/entity-registration",
    hrefLabel: "Start SAM.gov registration",
  },
  {
    id: "naics",
    title: "Confirm your NAICS codes",
    summary: "NAICS tells the government what industry you are in. Bids are filtered by these codes.",
    detail:
      "Pick the codes that match what you actually do. You can list multiple codes on your SAM profile. BrandLxft maps your industry to the most common federal codes below.",
    autoComplete: "viewed_naics",
  },
  {
    id: "find",
    title: "Connect SAM.gov & import live bids",
    summary: "Attach your SAM.gov API key once — BrandLxft pulls open solicitations matched to your NAICS and state.",
    detail:
      "Go to Settings → SAM.gov integration (or connect during signup Step 4). After connecting, live bids appear in your pipeline automatically. You can also browse SAM.gov manually for Contract Opportunities.",
    href: "/settings#sam-gov-api",
    hrefLabel: "Connect SAM.gov in Settings",
    autoComplete: "has_federal_opportunities",
  },
  {
    id: "capability",
    title: "Write a one-page capability statement",
    summary: "A short PDF intro: who you are, what you do, past performance, differentiators, and contact info.",
    detail:
      "Contracting officers read these before inviting you to bid. Keep it to one page. Include your UEI, NAICS codes, small business certifications, and 2–3 relevant projects.",
  },
  {
    id: "bid",
    title: "Start with small contracts ($10K–$250K)",
    summary: "Micro-purchases and simplified acquisitions have less paperwork. Win one, then grow.",
    detail:
      "Do not start with a $50M IDIQ. Target task orders, base maintenance contracts, and set-aside solicitations in your state. Subcontracting under a larger prime is also a valid entry path.",
    href: "https://www.usaspending.gov/search",
    hrefLabel: "See who won similar contracts (USAspending)",
  },
];

export const FEDERAL_GLOSSARY: Array<{ term: string; plain: string }> = [
  { term: "SAM.gov", plain: "Where you register as a vendor and find open bids." },
  { term: "UEI", plain: "Your company's unique ID in SAM — like a federal EIN for contracting." },
  { term: "NAICS", plain: "Industry code the government uses to categorize your business." },
  { term: "PIID", plain: "A specific contract number — not a company name." },
  { term: "Set-aside", plain: "A bid reserved for small or disadvantaged businesses only." },
  { term: "Capability statement", plain: "One-page company resume for contracting officers." },
  { term: "Solicitation", plain: "An open bid you can respond to before the deadline." },
];

export function getFederalWorkContext(business: Business) {
  const industry = business.input.industryCategory ?? business.input.industry;
  const naicsCodes = getNaicsForIndustry(business.input.industryCategory ?? business.input.industry);
  const state = parseStateCode(business.input.location);
  const market = getMarketStatsForNaics(naicsCodes);
  const federalOpportunities = business.opportunities.filter((o) => o.type === "government_contract");

  return {
    industry,
    location: business.input.location,
    state: state ?? null,
    naicsCodes: naicsCodes.map((code) => ({
      code,
      label: describeNaics(code),
    })),
    marketStats: market,
    federalOpportunityCount: federalOpportunities.length,
    isHomeServicesTrade: /home services|landscaping|hvac|roofing|plumbing|cleaning|janitorial/i.test(
      `${industry} ${business.input.industry} ${business.input.productsServices}`,
    ),
  };
}

export function buildCapabilityStatement(business: Business): string {
  const ctx = getFederalWorkContext(business);
  const { input, profile } = business;
  const naicsLine = ctx.naicsCodes.map((n) => `${n.code} (${n.label})`).join("; ");
  const strengths = profile.strengths.slice(0, 3).join("; ") || "Reliable service delivery and responsive customer communication.";
  const differentiators =
    profile.brandPositioning ||
    `${input.businessName} delivers ${input.productsServices.toLowerCase()} for ${input.targetCustomer.toLowerCase()}.`;

  return `CAPABILITY STATEMENT — ${input.businessName.toUpperCase()}

Core competencies
${input.productsServices}

NAICS
${naicsLine}

Service area
${input.location}${ctx.state ? ` (${ctx.state})` : ""} and surrounding federal facilities.

Differentiators
${differentiators}

Past performance / experience
• [Add 2–3 projects: client, scope, dollar value, year]
• [Include any government, institutional, or commercial reference accounts]

Company data
• Legal name: ${input.businessName}
• UEI: [Add after SAM.gov registration]
• Business size: Small business
• Contact: [Name, phone, email]

Why choose us
${strengths}

Certifications (if applicable)
• [8(a), HUBZone, SDVOSB, WOSB, or state/local certs — or "None at this time"]

References available upon request.`;
}
