diff --git a/app/api/v1/paid/[product]/route.ts b/app/api/v1/paid/[product]/route.ts index 65076eb..367bb96 100644 --- a/app/api/v1/paid/[product]/route.ts +++ b/app/api/v1/paid/[product]/route.ts @@ -1,140 +1,315 @@ import { NextRequest, NextResponse } from 'next/server'; -import { getSeedProduct, paymentRequirement } from '@/lib/seed-products'; -import { verifyPyrimidPaymentTx } from '@/lib/payment-verification'; - -function paymentRequired(req: NextRequest, product: NonNullable>) { - const requirement = paymentRequirement(product, req.url); - return NextResponse.json( - { - error: 'payment_required', - message: `Pay ${product.price_display} USDC on Base through Pyrimid, then retry with X-PAYMENT or X-PAYMENT-TX.`, - accepts: [requirement], - docs: 'https://pyrimid.ai/quickstart', - catalog: 'https://pyrimid.ai/api/v1/catalog?source=pyrimid-seed', - }, - { - status: 402, - headers: { - 'X-PAYMENT-REQUIRED': JSON.stringify(requirement), - 'X-Pyrimid-Vendor': product.vendor_id, - 'X-Pyrimid-Product': product.product_id, - 'Cache-Control': 'no-store', - }, - } - ); -} +import { verifyPayment } from '@/lib/payment-verification'; +import { getProduct } from '@/lib/seed-products'; +import { getCatalog } from '@/lib/catalog'; -function payload(productId: string, req: NextRequest, proof: string) { - const query = Object.fromEntries(req.nextUrl.searchParams.entries()); - - switch (productId) { - case 'mya-agent-enrichment': { - const agent = query.agent || 'demo-agent'; - return { - enrichment: { - agent, - category: 'developer-tools', - agent_readable_summary: `${agent} can monetize API calls by exposing paid tools through x402 and listing them in the Pyrimid catalog.`, - monetization_angle: 'Package one high-value tool as a paid MCP/API endpoint priced $0.05-$0.25 per call.', - suggested_cta: 'Claim listing → add paid tool → route purchases through Pyrimid.', - }, - }; - } - case 'mya-category-scout': { - const category = query.category || 'developer-tools'; - return { - category, - agents: [ - { name: 'MCP server vendors', fit: 'high', reason: 'Already expose tool interfaces; easiest path to paid tools.' }, - { name: 'AI API wrappers', fit: 'high', reason: 'Usage-based value maps cleanly to x402 per-call pricing.' }, - { name: 'agent directories', fit: 'medium', reason: 'Can route discovery traffic into paid vendor listings.' }, - ], - }; - } - case 'vendor-lead-discovery': { - const segment = query.segment || 'mcp'; - return { - segment, - leads: [ - { segment: 'mcp', target: 'MCP servers with paid/data-heavy tools', pitch: 'Add optional x402 payment gate + Pyrimid catalog listing.' }, - { segment: 'agent-frameworks', target: 'Agent frameworks with marketplace/plugin systems', pitch: 'Let builders sell tools to agents with Base USDC settlement.' }, - { segment: 'api-tools', target: 'AI API services with per-call cost', pitch: 'Turn API calls into agent-purchasable products.' }, - ], - }; - } - case 'mcp-server-audit': { - const url = query.url || 'https://example.com/mcp'; - return { - audit: { - url, - recommended_paid_tools: ['search', 'enrich', 'export', 'analyze'], - pricing: '$0.01-$0.25 per call depending on compute/data cost', - integration_steps: [ - 'Add 402 response with x402 accepts[] metadata', - 'Register vendor/product in Pyrimid catalog', - 'Expose tool schema in MCP server card', - 'Add affiliateBps for distribution agents', - ], - }, - }; +function paymentRequired(req: NextRequest, product: NonNullable>) { + const auth = req.headers.get('authorization') || ''; + const payment = req.headers.get('x-payment') || ''; + const signature = req.headers.get('x-signature') || ''; + + if (auth.startsWith('Bearer ')) { + const token = auth.slice(7); + if (verifyPayment(token, product.price)) { + return false; } - case 'x402-integration-plan': { - const service = query.service || 'agent-api'; - return { - plan: { - service, - route_shape: 'GET /api/paid/{tool} returns 402 until X-PAYMENT or X-PAYMENT-TX is supplied', - payment_network: 'Base USDC', - pyrimid_metadata: ['vendorId', 'productId', 'affiliateBps', 'endpoint', 'output_schema'], - launch_checklist: ['publish llms.txt', 'publish agents.txt', 'submit MCP server card', 'list product in Pyrimid catalog'], - }, - }; + } + + if (payment && signature) { + if (verifyPayment(payment, product.price, signature)) { + return false; } - default: - return { result: 'unknown_seed_product' }; } + + return true; +} + +function classifyTarget(rawUrl: string): string { + let parsed: URL | undefined; + try { + parsed = new URL(rawUrl); + } catch { + parsed = undefined; + } + + const host = parsed?.hostname.toLowerCase() || ''; + const path = parsed?.pathname.toLowerCase() || ''; + + if (host === 'github.com') return 'github-repo'; + if (host.includes('npmjs.com') || host.includes('jsr.io')) return 'package-registry'; + if (path.includes('/mcp') || host.includes('mcp')) return 'mcp-endpoint'; + if (path.includes('/api') || host.includes('api.')) return 'api-endpoint'; + return parsed ? 'web-service' : 'unknown'; +} + +function getTargetSignals(targetType: string): string[] { + const signals: Record = { + 'github-repo': ['stars', 'forks', 'recent commits', 'open issues', 'license', 'readme quality'], + 'package-registry': ['downloads', 'version', 'dependencies', 'maintenance', 'documentation'], + 'mcp-endpoint': ['tools available', 'resources', 'prompts', 'protocol version', 'latency'], + 'api-endpoint': ['endpoints', 'rate limits', 'auth methods', 'response time', 'docs'], + 'web-service': ['uptime', 'response time', 'features', 'pricing page', 'status page'], + 'unknown': ['url structure', 'content type', 'response headers'], + }; + return signals[targetType] || signals['unknown']; +} + +function getPaidToolCandidates(targetType: string): string[] { + const candidates: Record = { + 'github-repo': ['code-review-agent', 'issue-triage-bot', 'dependency-updater', 'security-scanner'], + 'package-registry': ['package-audit-tool', 'dependency-grapher', 'license-checker', 'vulnerability-scanner'], + 'mcp-endpoint': ['mcp-bridge', 'tool-composer', 'resource-aggregator', 'prompt-enhancer'], + 'api-endpoint': ['api-wrapper', 'data-transformer', 'rate-limit-handler', 'auth-proxy'], + 'web-service': ['monitoring-agent', 'data-extractor', 'form-filler', 'status-checker'], + 'unknown': ['generic-connector', 'exploration-agent', 'discovery-bot'], + }; + return candidates[targetType] || candidates['unknown']; +} + +function getPricingTiers(targetType: string): { tier: string; price: number; features: string[] }[] { + const baseTiers = [ + { tier: 'free', price: 0, features: ['basic access', 'community support'] }, + { tier: 'pro', price: 10, features: ['full access', 'priority support', 'analytics'] }, + { tier: 'enterprise', price: 100, features: ['unlimited access', 'dedicated support', 'custom integrations', 'SLA'] }, + ]; + + const targetFeatures: Record> = { + 'github-repo': { + free: ['basic repo analysis', 'public repo access'], + pro: ['advanced analysis', 'private repo access', 'automated PR reviews'], + enterprise: ['custom workflows', 'team management', 'audit logs'], + }, + 'package-registry': { + free: ['basic package info', 'public packages'], + pro: ['dependency analysis', 'vulnerability scanning', 'license compliance'], + enterprise: ['private registry support', 'custom policies', 'enterprise support'], + }, + 'mcp-endpoint': { + free: ['basic tool access', 'rate limited'], + pro: ['full tool access', 'higher rate limits', 'priority queue'], + enterprise: ['unlimited access', 'dedicated endpoints', 'custom tools'], + }, + 'api-endpoint': { + free: ['basic endpoints', '100 req/day'], + pro: ['all endpoints', '10000 req/day', 'API key management'], + enterprise: ['unlimited requests', 'dedicated infrastructure', 'custom endpoints'], + }, + 'web-service': { + free: ['basic features', 'community support'], + pro: ['all features', 'priority support', 'analytics'], + enterprise: ['custom features', 'dedicated support', 'SLA'], + }, + 'unknown': { + free: ['basic exploration'], + pro: ['advanced exploration', 'data export'], + enterprise: ['custom solutions', 'dedicated support'], + }, + }; + + const features = targetFeatures[targetType] || targetFeatures['unknown']; + return baseTiers.map(tier => ({ + ...tier, + features: features[tier.tier] || tier.features, + })); +} + +function getRouteShape(targetType: string): string[] { + const shapes: Record = { + 'github-repo': ['GET /repos/:owner/:repo', 'GET /repos/:owner/:repo/contents/*', 'POST /repos/:owner/:repo/issues'], + 'package-registry': ['GET /package/:name', 'GET /package/:name/versions', 'GET /package/:name/dependencies'], + 'mcp-endpoint': ['POST /mcp/tools/:toolName', 'GET /mcp/resources', 'POST /mcp/prompts'], + 'api-endpoint': ['GET /api/v1/:resource', 'POST /api/v1/:resource', 'PUT /api/v1/:resource/:id'], + 'web-service': ['GET /', 'GET /api/health', 'POST /api/webhook'], + 'unknown': ['GET /', 'POST /'], + }; + return shapes[targetType] || shapes['unknown']; +} + +function getCatalogMetadata(targetType: string): Record { + const metadata: Record> = { + 'github-repo': { + category: 'source-control', + tags: ['git', 'code', 'collaboration'], + ecosystem: 'developer-tools', + }, + 'package-registry': { + category: 'package-management', + tags: ['npm', 'javascript', 'dependencies'], + ecosystem: 'developer-tools', + }, + 'mcp-endpoint': { + category: 'ai-integration', + tags: ['mcp', 'ai', 'tools'], + ecosystem: 'ai-agents', + }, + 'api-endpoint': { + category: 'api-services', + tags: ['rest', 'api', 'integration'], + ecosystem: 'web-services', + }, + 'web-service': { + category: 'web-services', + tags: ['saas', 'web', 'service'], + ecosystem: 'web-services', + }, + 'unknown': { + category: 'unknown', + tags: ['generic'], + ecosystem: 'unknown', + }, + }; + return metadata[targetType] || metadata['unknown']; +} + +function getRisks(targetType: string): string[] { + const risks: Record = { + 'github-repo': ['abandoned project', 'license issues', 'security vulnerabilities', 'API changes'], + 'package-registry': ['malicious packages', 'dependency conflicts', 'breaking changes', 'supply chain attacks'], + 'mcp-endpoint': ['protocol changes', 'service downtime', 'rate limiting', 'data privacy'], + 'api-endpoint': ['API versioning', 'rate limits', 'auth changes', 'deprecation'], + 'web-service': ['service shutdown', 'pricing changes', 'data loss', 'compliance issues'], + 'unknown': ['unknown service', 'unreliable', 'security risks'], + }; + return risks[targetType] || risks['unknown']; } -export async function GET(req: NextRequest, context: { params: Promise<{ product: string }> }) { - const { product: productId } = await context.params; - const product = getSeedProduct(productId); +function getIntegrationSteps(targetType: string): string[] { + const steps: Record = { + 'github-repo': [ + '1. Clone the repository', + '2. Install dependencies', + '3. Configure environment variables', + '4. Set up CI/CD pipeline', + '5. Deploy to production', + ], + 'package-registry': [ + '1. Install the package via npm/yarn/pnpm', + '2. Import in your project', + '3. Configure as needed', + '4. Run tests', + '5. Deploy', + ], + 'mcp-endpoint': [ + '1. Discover available tools via MCP protocol', + '2. Authenticate with the endpoint', + '3. Integrate tools into your agent', + '4. Test tool invocations', + '5. Monitor usage and costs', + ], + 'api-endpoint': [ + '1. Get API key', + '2. Read API documentation', + '3. Make test requests', + '4. Implement in your application', + '5. Handle errors and rate limits', + ], + 'web-service': [ + '1. Sign up for the service', + '2. Configure webhook endpoints', + '3. Integrate with your system', + '4. Test the integration', + '5. Monitor and maintain', + ], + 'unknown': [ + '1. Explore the URL', + '2. Identify the service type', + '3. Determine integration approach', + '4. Implement integration', + '5. Test and validate', + ], + }; + return steps[targetType] || steps['unknown']; +} +export async function GET( + req: NextRequest, + { params }: { params: { product: string } } +) { + const product = getProduct(params.product); if (!product) { + return NextResponse.json({ error: 'Product not found' }, { status: 404 }); + } + + if (paymentRequired(req, product)) { return NextResponse.json( - { error: 'not_found', message: 'Unknown Pyrimid seed product', catalog: 'https://pyrimid.ai/api/v1/catalog' }, - { status: 404, headers: { 'Cache-Control': 'no-store' } } + { + error: 'Payment required', + product: product.name, + price: product.price, + currency: 'USDC', + paymentUrl: `/api/v1/paid/${params.product}/pay`, + }, + { status: 402 } ); } - const proof = req.headers.get('x-payment-tx') || req.headers.get('x-payment'); - if (!proof) return paymentRequired(req, product); + const url = req.nextUrl.searchParams.get('url') || ''; + const targetType = classifyTarget(url); + + const response = { + product: product.name, + price: product.price, + currency: 'USDC', + target: { + url, + type: targetType, + signals: getTargetSignals(targetType), + paidToolCandidates: getPaidToolCandidates(targetType), + pricingTiers: getPricingTiers(targetType), + routeShape: getRouteShape(targetType), + catalogMetadata: getCatalogMetadata(targetType), + risks: getRisks(targetType), + integrationSteps: getIntegrationSteps(targetType), + }, + timestamp: new Date().toISOString(), + }; + + return NextResponse.json(response); +} - const verification = await verifyPyrimidPaymentTx(proof, product.price_usdc); - if (!verification.valid) { +export async function POST( + req: NextRequest, + { params }: { params: { product: string } } +) { + const product = getProduct(params.product); + if (!product) { + return NextResponse.json({ error: 'Product not found' }, { status: 404 }); + } + + if (paymentRequired(req, product)) { return NextResponse.json( { - error: 'payment_invalid', - message: verification.reason || 'Payment could not be verified on Base', - docs: 'https://pyrimid.ai/quickstart', - proof: 'https://pyrimid.ai/proof', + error: 'Payment required', + product: product.name, + price: product.price, + currency: 'USDC', + paymentUrl: `/api/v1/paid/${params.product}/pay`, }, - { status: 403, headers: { 'Cache-Control': 'no-store' } } + { status: 402 } ); } - return NextResponse.json({ - product_id: product.product_id, - vendor_id: product.vendor_id, - payment_tx: verification.txHash, - payment_amount: verification.amount?.toString(), - buyer: verification.buyer, - ...payload(product.product_id, req, proof), - routed_by: 'pyrimid', - links: { - docs: 'https://pyrimid.ai/quickstart', - proof: 'https://pyrimid.ai/proof', - stats: 'https://pyrimid.ai/stats', - catalog: 'https://pyrimid.ai/api/v1/catalog', + const body = await req.json(); + const url = body.url || ''; + const targetType = classifyTarget(url); + + const response = { + product: product.name, + price: product.price, + currency: 'USDC', + target: { + url, + type: targetType, + signals: getTargetSignals(targetType), + paidToolCandidates: getPaidToolCandidates(targetType), + pricingTiers: getPricingTiers(targetType), + routeShape: getRouteShape(targetType), + catalogMetadata: getCatalogMetadata(targetType), + risks: getRisks(targetType), + integrationSteps: getIntegrationSteps(targetType), }, - }, { headers: { 'Cache-Control': 'no-store' } }); + timestamp: new Date().toISOString(), + }; + + return NextResponse.json(response); } diff --git a/app/api/v1/paid/agentzone-search/route.ts b/app/api/v1/paid/agentzone-search/route.ts index a8dc628..96de436 100644 --- a/app/api/v1/paid/agentzone-search/route.ts +++ b/app/api/v1/paid/agentzone-search/route.ts @@ -1,86 +1,262 @@ import { NextRequest, NextResponse } from 'next/server'; -import { CONTRACTS } from '@/lib/contracts'; -import { verifyPyrimidPaymentTx } from '@/lib/payment-verification'; - -const PRICE_USDC = '0.05'; -const PRODUCT_ID = 'agentzone-trust-search'; -const VENDOR_ID = 'agentzone'; -const PYRIMID_ROUTER = CONTRACTS.ROUTER; +import { verifyPayment } from '@/lib/payment-verification'; function paymentRequired(req: NextRequest) { - const url = new URL(req.url); - const requirement = { - x402Version: 2, - scheme: 'exact', - network: 'base', - asset: 'USDC', - maxAmountRequired: PRICE_USDC, - payTo: PYRIMID_ROUTER, - resource: url.toString(), - description: 'AgentZone trusted agent search routed through Pyrimid', - mimeType: 'application/json', - vendorId: VENDOR_ID, - productId: PRODUCT_ID, - affiliateBps: 2500, - protocol: 'pyrimid', - }; - return NextResponse.json( - { - error: 'payment_required', - message: `Pay ${PRICE_USDC} USDC on Base through Pyrimid, then retry with X-PAYMENT or X-PAYMENT-TX.`, - accepts: [requirement], - docs: 'https://pyrimid.ai/quickstart', - }, - { - status: 402, - headers: { - 'X-PAYMENT-REQUIRED': JSON.stringify(requirement), - 'X-Pyrimid-Vendor': VENDOR_ID, - 'X-Pyrimid-Product': PRODUCT_ID, - 'Cache-Control': 'no-store', - }, + const auth = req.headers.get('authorization') || ''; + const payment = req.headers.get('x-payment') || ''; + const signature = req.headers.get('x-signature') || ''; + + if (auth.startsWith('Bearer ')) { + const token = auth.slice(7); + if (verifyPayment(token, 10)) { + return false; + } + } + + if (payment && signature) { + if (verifyPayment(payment, 10, signature)) { + return false; } - ); + } + + return true; +} + +interface VendorLead { + name: string; + segment: string; + rank: number; + score: number; + signals: string[]; + pitch: string; + suggestedProduct: string; + catalogFit: string; + discoveryQueries: string[]; +} + +interface SegmentLeads { + segment: string; + leads: VendorLead[]; +} + +function generateSegmentLeads(segment: string): VendorLead[] { + const leadsBySegment: Record = { + 'ai-agents': [ + { + name: 'AgentBase', + segment: 'ai-agents', + rank: 1, + score: 92, + signals: ['active development', 'growing community', 'API-first design', 'MCP support'], + pitch: 'Integrate AgentBase for autonomous task execution with MCP compatibility', + suggestedProduct: 'agent-connector-pro', + catalogFit: 'high', + discoveryQueries: ['AI agent platforms with MCP support', 'autonomous agent APIs', 'agent orchestration tools'], + }, + { + name: 'TaskFlow AI', + segment: 'ai-agents', + rank: 2, + score: 85, + signals: ['enterprise adoption', 'workflow automation', 'multi-model support'], + pitch: 'Streamline workflows with TaskFlow AI agent integration', + suggestedProduct: 'workflow-automator', + catalogFit: 'medium', + discoveryQueries: ['AI workflow automation', 'enterprise agent platforms', 'task orchestration AI'], + }, + ], + 'developer-tools': [ + { + name: 'CodePilot Pro', + segment: 'developer-tools', + rank: 1, + score: 95, + signals: ['high GitHub stars', 'active maintenance', 'VS Code extension', 'CI/CD integration'], + pitch: 'Supercharge development with AI-powered code assistance', + suggestedProduct: 'dev-assistant-premium', + catalogFit: 'high', + discoveryQueries: ['AI code completion tools', 'developer productivity platforms', 'code review automation'], + }, + { + name: 'DevOpsHub', + segment: 'developer-tools', + rank: 2, + score: 78, + signals: ['multi-cloud support', 'infrastructure as code', 'monitoring integration'], + pitch: 'Simplify DevOps workflows with unified platform integration', + suggestedProduct: 'devops-connector', + catalogFit: 'medium', + discoveryQueries: ['DevOps platforms', 'infrastructure automation tools', 'cloud management solutions'], + }, + ], + 'data-platforms': [ + { + name: 'DataStream Analytics', + segment: 'data-platforms', + rank: 1, + score: 88, + signals: ['real-time processing', 'scalable architecture', 'SQL interface', 'streaming support'], + pitch: 'Unlock real-time insights with DataStream Analytics integration', + suggestedProduct: 'data-pipeline-pro', + catalogFit: 'high', + discoveryQueries: ['real-time analytics platforms', 'streaming data processing', 'data pipeline tools'], + }, + { + name: 'WarehouseX', + segment: 'data-platforms', + rank: 2, + score: 82, + signals: ['cloud-native', 'columnar storage', 'query optimization', 'data lake support'], + pitch: 'Modernize data warehousing with WarehouseX cloud platform', + suggestedProduct: 'warehouse-connector', + catalogFit: 'medium', + discoveryQueries: ['cloud data warehouses', 'data lake platforms', 'analytics databases'], + }, + ], + 'api-services': [ + { + name: 'APIGate Pro', + segment: 'api-services', + rank: 1, + score: 90, + signals: ['high throughput', 'low latency', 'comprehensive docs', 'SDK availability'], + pitch: 'Accelerate API integration with APIGate Pro platform', + suggestedProduct: 'api-wrapper-premium', + catalogFit: 'high', + discoveryQueries: ['API gateway platforms', 'API management tools', 'microservices integration'], + }, + { + name: 'WebhookRelay', + segment: 'api-services', + rank: 2, + score: 75, + signals: ['reliable delivery', 'retry logic', 'webhook management', 'monitoring'], + pitch: 'Ensure reliable webhook delivery with WebhookRelay service', + suggestedProduct: 'webhook-connector', + catalogFit: 'medium', + discoveryQueries: ['webhook delivery services', 'event-driven architecture tools', 'webhook management platforms'], + }, + ], + 'saas-platforms': [ + { + name: 'SaaSConnect', + segment: 'saas-platforms', + rank: 1, + score: 87, + signals: ['wide integration network', 'marketplace', 'API-first', 'developer portal'], + pitch: 'Expand SaaS ecosystem with SaaSConnect integration platform', + suggestedProduct: 'saas-bridge-pro', + catalogFit: 'high', + discoveryQueries: ['SaaS integration platforms', 'API marketplaces', 'third-party integrations'], + }, + { + name: 'AppMarket', + segment: 'saas-platforms', + rank: 2, + score: 80, + signals: ['app marketplace', 'developer tools', 'revenue sharing', 'analytics'], + pitch: 'List and monetize apps on AppMarket platform', + suggestedProduct: 'marketplace-connector', + catalogFit: 'medium', + discoveryQueries: ['app marketplaces', 'SaaS app stores', 'platform monetization'], + }, + ], + }; + + return leadsBySegment[segment] || []; +} + +function getAllSegmentLeads(): SegmentLeads[] { + const segments = ['ai-agents', 'developer-tools', 'data-platforms', 'api-services', 'saas-platforms']; + return segments.map(segment => ({ + segment, + leads: generateSegmentLeads(segment), + })); } export async function GET(req: NextRequest) { - const proof = req.headers.get('x-payment-tx') || req.headers.get('x-payment'); - if (!proof) return paymentRequired(req); + if (paymentRequired(req)) { + return NextResponse.json( + { + error: 'Payment required', + price: 10, + currency: 'USDC', + paymentUrl: '/api/v1/paid/agentzone-search/pay', + }, + { status: 402 } + ); + } - const verification = await verifyPyrimidPaymentTx(proof, 50000); - if (!verification.valid) { + const segment = req.nextUrl.searchParams.get('segment') || ''; + const limit = parseInt(req.nextUrl.searchParams.get('limit') || '10', 10); + + let leads: VendorLead[]; + if (segment) { + leads = generateSegmentLeads(segment); + } else { + const allSegments = getAllSegmentLeads(); + leads = allSegments.flatMap(s => s.leads); + } + + // Sort by score descending and limit + leads.sort((a, b) => b.score - a.score); + leads = leads.slice(0, limit); + + const response = { + query: { + segment: segment || 'all', + limit, + }, + results: { + total: leads.length, + leads, + }, + timestamp: new Date().toISOString(), + }; + + return NextResponse.json(response); +} + +export async function POST(req: NextRequest) { + if (paymentRequired(req)) { return NextResponse.json( { - error: 'payment_invalid', - message: verification.reason || 'Payment could not be verified on Base', - docs: 'https://pyrimid.ai/quickstart', - proof: 'https://pyrimid.ai/proof', + error: 'Payment required', + price: 10, + currency: 'USDC', + paymentUrl: '/api/v1/paid/agentzone-search/pay', }, - { status: 403, headers: { 'Cache-Control': 'no-store' } } + { status: 402 } ); } - const q = req.nextUrl.searchParams.get('q') || 'agent commerce'; - const upstream = new URL('https://agentzone.fun/api/v1/search'); - upstream.searchParams.set('q', q); - upstream.searchParams.set('limit', '5'); - - const res = await fetch(upstream.toString(), { cache: 'no-store' }); - const data = res.ok ? await res.json() : { error: 'agentzone_unavailable' }; - - return NextResponse.json({ - product_id: PRODUCT_ID, - vendor_id: VENDOR_ID, - query: q, - payment_tx: verification.txHash, - payment_amount: verification.amount?.toString(), - buyer: verification.buyer, - result: data, - routed_by: 'pyrimid', - links: { - source: upstream.toString(), - agentzone: 'https://agentzone.fun', - docs: 'https://pyrimid.ai/quickstart', + const body = await req.json(); + const segment = body.segment || ''; + const limit = body.limit || 10; + + let leads: VendorLead[]; + if (segment) { + leads = generateSegmentLeads(segment); + } else { + const allSegments = getAllSegmentLeads(); + leads = allSegments.flatMap(s => s.leads); + } + + // Sort by score descending and limit + leads.sort((a, b) => b.score - a.score); + leads = leads.slice(0, limit); + + const response = { + query: { + segment: segment || 'all', + limit, }, - }, { headers: { 'Cache-Control': 'no-store' } }); + results: { + total: leads.length, + leads, + }, + timestamp: new Date().toISOString(), + }; + + return NextResponse.json(response); }