Elffuss BraidHub

kikocis/osiris public

master · 5.8 KiBRawPermalink
1import { NextResponse } from 'next/server';
2
3/**
4 * OSIRIS — Region Dossier API
5 * Provides country intelligence for any coordinate (right-click on map)
6 * Fix #115: Steps 2-4 now run in parallel via Promise.allSettled
7 */
8
9export async function GET(request: Request) {
10 const { searchParams } = new URL(request.url);
11 const lat = parseFloat(searchParams.get('lat') || '0');
12 const lng = parseFloat(searchParams.get('lng') || '0');
13
14 try {
15 // Step 1: Reverse geocode to get country (must complete first — other steps depend on it)
16 const geoRes = await fetch(
17 `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&zoom=5&addressdetails=1`,
18 {
19 signal: AbortSignal.timeout(8000),
20 headers: { 'User-Agent': 'OsirisIntelPlatform/1.0' },
21 }
22 );
23
24 let countryName = '';
25 let countryCode = '';
26 let locationInfo: any = {};
27
28 if (geoRes.ok) {
29 const geoData = await geoRes.json();
30 const addr = geoData.address || {};
31 countryName = addr.country || '';
32 countryCode = addr.country_code?.toUpperCase() || '';
33 locationInfo = {
34 city: addr.city || addr.town || addr.village || '',
35 state: addr.state || addr.region || '',
36 country: countryName,
37 country_code: countryCode,
38 display_name: geoData.display_name,
39 };
40 }
41
42 // Steps 2–4: Run in PARALLEL after geocode (Fixes #115 — was a sequential waterfall)
43 const [countryResult, wikiResult, hosResult] = await Promise.allSettled([
44
45 // Step 2: Fetch country details from RestCountries
46 (async () => {
47 if (!countryCode) return null;
48 try {
49 const res = await fetch(
50 `https://restcountries.com/v3.1/alpha/${countryCode}?fields=name,capital,population,area,region,subregion,languages,currencies,flag,flags,timezones`,
51 { signal: AbortSignal.timeout(5000) }
52 );
53 if (res.ok) return await res.json();
54 } catch (e) { console.warn('[OSIRIS] Country fetch error:', e instanceof Error ? e.message : e); }
55 return null;
56 })(),
57
58 // Step 3: Fetch Wikipedia summary
59 (async () => {
60 const wikiQuery = locationInfo.city || countryName;
61 if (!wikiQuery) return null;
62 try {
63 const res = await fetch(
64 `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(wikiQuery)}`,
65 { signal: AbortSignal.timeout(5000) }
66 );
67 if (res.ok) {
68 const wiki = await res.json();
69 return {
70 title: wiki.title,
71 extract: wiki.extract?.substring(0, 500),
72 thumbnail: wiki.thumbnail?.source,
73 };
74 }
75 } catch (e) { console.warn('[OSIRIS] Wikipedia fetch error:', e instanceof Error ? e.message : e); }
76 return null;
77 })(),
78
79 // Step 4: Fetch head of state from Wikidata SPARQL
80 (async () => {
81 if (!countryName) return null;
82 try {
83 // Sanitize country name for SPARQL string literal
84 const safe = countryName.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
85 const sparql = `SELECT ?leader ?leaderLabel ?positionLabel WHERE {
86 ?country wdt:P31 wd:Q6256;
87 rdfs:label "${safe}"@en;
88 wdt:P6 ?leader.
89 OPTIONAL { ?leader wdt:P39 ?position. }
90 SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
91 } LIMIT 1`;
92 const res = await fetch(
93 `https://query.wikidata.org/sparql?format=json&query=${encodeURIComponent(sparql)}`,
94 {
95 signal: AbortSignal.timeout(5000),
96 headers: { 'User-Agent': 'OsirisIntelPlatform/1.0' },
97 }
98 );
99 if (res.ok) {
100 const wd = await res.json();
101 const binding = wd.results?.bindings?.[0];
102 if (binding) {
103 return {
104 name: binding.leaderLabel?.value,
105 position: binding.positionLabel?.value || 'Head of State',
106 };
107 }
108 }
109 } catch (e) { console.warn('[OSIRIS] Wikidata fetch error:', e instanceof Error ? e.message : e); }
110 return null;
111 })(),
112 ]);
113
114 const countryData = countryResult.status === 'fulfilled' ? countryResult.value : null;
115 const wikiSummary = wikiResult.status === 'fulfilled' ? wikiResult.value : null;
116 const headOfState = hosResult.status === 'fulfilled' ? hosResult.value : null;
117
118 return NextResponse.json({
119 coordinates: { lat, lng },
120 location: locationInfo,
121 country: countryData ? {
122 name: countryData.name?.common,
123 official_name: countryData.name?.official,
124 capital: countryData.capital?.[0],
125 population: countryData.population,
126 area: countryData.area,
127 region: countryData.region,
128 subregion: countryData.subregion,
129 languages: countryData.languages ? Object.values(countryData.languages) : [],
130 currencies: countryData.currencies
131 ? Object.entries(countryData.currencies).map(([code, info]: [string, any]) => `${info.name} (${info.symbol || code})`)
132 : [],
133 flag: countryData.flag,
134 flag_url: countryData.flags?.svg,
135 timezones: countryData.timezones,
136 } : null,
137 head_of_state: headOfState,
138 wikipedia: wikiSummary,
139 timestamp: new Date().toISOString(),
140 }, {
141 headers: {
142 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=7200',
143 },
144 });
145 } catch (error) {
146 console.error('Region dossier error:', error);
147 return NextResponse.json({ error: 'Failed to fetch region data' }, { status: 500 });
148 }
149}