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
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
"""backend/api/search.py — Search, fetch-page, analyze-image proxy routes (S358).

S358: proxy_search web branch ora usa asyncio.gather per eseguire Wikipedia, DDG HTML,
SearXNG e DDG Instant Answer in parallelo invece di in cascata. Worst case: ~8s → ~8s
(stesso bound sul provider più lento), ma caso medio: ~3s invece di ~20s.
"""
import os, asyncio, html, json
import re as _re
import urllib.request, urllib.parse
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from .auth_guard import require_role, AuthRole

import logging
_logger = logging.getLogger("api.search")

router = APIRouter()


class SearchRequest(BaseModel):
    query:  str
    type:   str   = "web"
    limit:  int   = 10
    lang:   Optional[str] = None


class FetchPageRequest(BaseModel):
    url: str


class AnalyzeImageRequest(BaseModel):
    dataUrl:  str
    filename: Optional[str] = "image"
    question: Optional[str] = None


# ── Helpers ────────────────────────────────────────────────────────────────────

def _clean_html(raw: str, max_chars: int = 20_000) -> tuple[str, list[str]]:
    code_blocks: list[str] = []
    for m in _re.findall(r'<(?:pre|code)[^>]*>(.*?)</(?:pre|code)>', raw, _re.S | _re.I):
        cleaned = _re.sub(r'<[^>]+>', '', m)
        decoded = html.unescape(cleaned).strip()
        if decoded:
            code_blocks.append(decoded[:2000])
    raw = _re.sub(r'<(script|style)[^>]*>.*?</\1>', '', raw, flags=_re.S | _re.I)
    text = _re.sub(r'<[^>]+>', ' ', raw)
    text = _re.sub(r'\s+', ' ', html.unescape(text)).strip()
    return text[:max_chars], code_blocks[:20]


def _get_title(raw: str) -> str:
    m = _re.search(r'<title[^>]*>(.*?)</title>', raw, _re.S | _re.I)
    if m:
        return html.unescape(_re.sub(r'<[^>]+>', '', m.group(1))).strip()[:200]  # S580: 120→200
    return ""


# ── Web search coroutines (S358: run in parallel via asyncio.gather) ───────────

async def _wiki_search(q: str, limit: int) -> list[dict]:
    try:
        wiki_qs = urllib.parse.urlencode({
            'action': 'query', 'list': 'search', 'srsearch': q,
            'format': 'json', 'utf8': '1', 'srlimit': min(limit, 5), 'srnamespace': '0',
        })
        wiki_req = urllib.request.Request(
            f'https://en.wikipedia.org/w/api.php?{wiki_qs}',
            headers={'User-Agent': 'agente-ai/3.1'},
        )
        wiki_data = await asyncio.to_thread(
            lambda: json.loads(urllib.request.urlopen(wiki_req, timeout=6).read())
        )
        results = []
        for item in wiki_data.get('query', {}).get('search', [])[:limit]:
            snippet = _re.sub(r'<[^>]+>', '', item.get('snippet', ''))
            results.append({
                'title':   item.get('title', ''),
                'url':     'https://en.wikipedia.org/wiki/' + item.get('title', '').replace(' ', '_'),
                # S598: snippet 300→500 — snippet Wikipedia troncati (spesso > 300 chars)
                'snippet': html.unescape(snippet)[:500],
                'source':  'web',
            })
        return results
    except Exception:
        return []


async def _ddg_html_search(q: str, limit: int) -> list[dict]:
    try:
        ddg_qs = urllib.parse.urlencode({'q': q, 'kl': 'it-it'})
        ddg_req = urllib.request.Request(
            f'https://html.duckduckgo.com/html/?{ddg_qs}',
            headers={
                'User-Agent':      'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Safari/604.1',
                'Accept':          'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language': 'it-IT,it;q=0.9,en;q=0.8',
            },
        )
        raw_ddg       = await asyncio.to_thread(
            lambda: urllib.request.urlopen(ddg_req, timeout=10).read().decode('utf-8', errors='replace')
        )
        links         = _re.findall(r'class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)</a>', raw_ddg, _re.S)
        snippets_raw  = _re.findall(r'class="result__snippet"[^>]*>(.*?)</a>', raw_ddg, _re.S)
        results = []
        for i, (href, title_html) in enumerate(links[:limit]):
            title   = html.unescape(_re.sub(r'<[^>]+>', '', title_html)).strip()
            snippet = html.unescape(_re.sub(r'<[^>]+>', '', snippets_raw[i] if i < len(snippets_raw) else '')).strip()
            if title and href.startswith('http'):
                # S598: snippet 300→500 — snippet DDG HTML troncati
                results.append({'title': title, 'url': href, 'snippet': snippet[:500], 'source': 'web'})
        return results
    except Exception:
        return []


async def _searxng_search(q: str, limit: int) -> list[dict]:
    try:
        sx_qs  = urllib.parse.urlencode({'q': q, 'format': 'json', 'language': 'en', 'safesearch': '0', 'categories': 'general'})
        sx_req = urllib.request.Request(
            f'https://searx.be/search?{sx_qs}',
            headers={'User-Agent': 'agente-ai/3.1', 'Accept': 'application/json'},
        )
        sx_data = await asyncio.to_thread(
            lambda: json.loads(urllib.request.urlopen(sx_req, timeout=8).read())
        )
        return [
            {
                'title':   item.get('title', '')[:200],  # S580: 100→200
                'url':     item.get('url', ''),
                # S598: snippet 300→500 — SearXNG content troncato
                'snippet': item.get('content', '')[:500],
                'source':  'web',
            }
            for item in sx_data.get('results', [])[:limit]
        ]
    except Exception:
        return []


async def _brave_search(q: str, limit: int) -> list[dict]:
    """S601: Brave Search API — attivo solo se BRAVE_SEARCH_API_KEY impostata."""
    api_key = os.environ.get("BRAVE_SEARCH_API_KEY", "")
    if not api_key:
        return []
    try:
        import httpx as _httpx_b
        qs = urllib.parse.urlencode({"q": q, "count": min(limit, 20), "search_lang": "it"})
        async with _httpx_b.AsyncClient(timeout=8.0) as c:
            r = await c.get(
                f"https://api.search.brave.com/res/v1/web/search?{qs}",
                headers={
                    "Accept":              "application/json",
                    "Accept-Encoding":     "gzip",
                    "X-Subscription-Token": api_key,
                },
            )
            data = r.json()
        return [
            {
                "title":   item.get("title", "")[:200],
                "url":     item.get("url", ""),
                "snippet": item.get("description", "")[:500],
                "source":  "web",
            }
            for item in data.get("web", {}).get("results", [])[:limit]
            if item.get("url")
        ]
    except Exception:
        return []


async def _tavily_search(q: str, limit: int) -> list[dict]:
    """S601: Tavily Search API — attivo solo se TAVILY_API_KEY impostata."""
    api_key = os.environ.get("TAVILY_API_KEY", "")
    if not api_key:
        return []
    try:
        import httpx as _httpx_t
        async with _httpx_t.AsyncClient(timeout=10.0) as c:
            r = await c.post(
                "https://api.tavily.com/search",
                json={
                    "api_key":      api_key,
                    "query":        q,
                    "max_results":  min(limit, 10),
                    "search_depth": "basic",
                },
                headers={"Content-Type": "application/json"},
            )
            data = r.json()
        return [
            {
                "title":   item.get("title", "")[:200],
                "url":     item.get("url", ""),
                "snippet": item.get("content", "")[:500],
                "source":  "web",
            }
            for item in data.get("results", [])[:limit]
            if item.get("url")
        ]
    except Exception:
        return []


async def _ddg_instant_search(q: str, limit: int) -> list[dict]:
    try:
        qs  = urllib.parse.urlencode({'q': q, 'format': 'json', 'no_html': '1', 'no_redirect': '1', 'skip_disambig': '1'})
        req = urllib.request.Request(
            f'https://api.duckduckgo.com/?{qs}',
            headers={'User-Agent': 'agente-ai/3.1'},
        )
        data = await asyncio.to_thread(
            lambda: json.loads(urllib.request.urlopen(req, timeout=8).read())
        )
        results = []
        if data.get('AbstractText'):
            results.append({
                'title':   data.get('Heading', q),
                'url':     data.get('AbstractURL', ''),
                # S598: snippet 300→500 — DDG instant AbstractText troncato
                'snippet': data['AbstractText'][:500],
                'source':  'web',
            })
        for topic in data.get('RelatedTopics', [])[:limit]:
            if isinstance(topic, dict) and topic.get('Text'):
                results.append({
                    'title':   topic.get('Text', '')[:200],  # S580: 80→200
                    'url':     topic.get('FirstURL', ''),
                    'snippet': topic.get('Text', '')[:300],  # S580: 200→300
                    'source':  'web',
                })
        return results
    except Exception:
        return []


# ── Search ─────────────────────────────────────────────────────────────────────

@router.post('/api/search')
async def proxy_search(req: SearchRequest, role: AuthRole = Depends(require_role(AuthRole.MACHINE))):
    q = req.query.strip()[:200]
    if not q:
        return {'results': []}

    results = []

    try:
        if req.type == "github_repo":
            qs = urllib.parse.urlencode({'q': q + (f' language:{req.lang}' if req.lang else ''), 'per_page': min(req.limit, 10)})
            url = f'https://api.github.com/search/repositories?{qs}'
            gh_req = urllib.request.Request(url, headers={'User-Agent': 'agente-ai/3.1', 'Accept': 'application/vnd.github+json'})
            gh_token = os.getenv('GITHUB_TOKEN', '')
            if gh_token:
                gh_req.add_header('Authorization', f'Bearer {gh_token}')
            def _do_gh():
                with urllib.request.urlopen(gh_req, timeout=8) as r:
                    return json.loads(r.read())
            data = await asyncio.to_thread(_do_gh)
            for item in data.get('items', [])[:req.limit]:
                results.append({
                    'title':   item.get('full_name', ''),
                    'url':     item.get('html_url', ''),
                    'snippet': (item.get('description') or '')[:300],  # S584: 200→300
                    'source':  'github',
                })

        elif req.type == "npm":
            qs = urllib.parse.urlencode({'text': q, 'size': min(req.limit, 20)})
            url = f'https://registry.npmjs.org/-/v1/search?{qs}'
            _npm_r = urllib.request.Request(url, headers={'User-Agent': 'agente-ai/3.1'})
            data = await asyncio.to_thread(lambda: json.loads(urllib.request.urlopen(_npm_r, timeout=8).read()))
            for obj in data.get('objects', [])[:req.limit]:
                pkg = obj.get('package', {})
                results.append({
                    'title':   pkg.get('name', ''),
                    'url':     f"https://www.npmjs.com/package/{pkg.get('name', '')}",
                    'snippet': pkg.get('description', '')[:300],  # S584: 200→300
                    'source':  'docs',
                })

        elif req.type == "pypi":
            encoded = urllib.parse.quote(q)
            url = f'https://pypi.org/pypi/{encoded}/json'
            try:
                _pypi_r = urllib.request.Request(url, headers={'User-Agent': 'agente-ai/3.1'})
                data = await asyncio.to_thread(lambda: json.loads(urllib.request.urlopen(_pypi_r, timeout=8).read()))
                info = data.get('info', {})
                results.append({
                    'title':   info.get('name', q),
                    'url':     info.get('project_url') or f'https://pypi.org/project/{q}/',
                    'snippet': (info.get('summary') or '')[:300],  # S584: 200→300
                    'source':  'docs',
                })
            except Exception as _exc:
                _logger.debug("[search] silenced %s", type(_exc).__name__)  # noqa: BLE001

        else:
            # S601: Brave+Tavily come provider primari se API key disponibile;
            # fallback automatico a Wikipedia+DDG+SearXNG se non configurati.
            _brave_res = await _brave_search(q, req.limit)
            _tavily_res = await _tavily_search(q, req.limit)
            if _brave_res or _tavily_res:
                # Provider premium disponibili → usa solo loro + Wikipedia per contesto enciclopedico
                batches = await asyncio.gather(
                    asyncio.sleep(0, result=_brave_res),
                    asyncio.sleep(0, result=_tavily_res),
                    _wiki_search(q, min(req.limit, 3)),
                    return_exceptions=True,
                )
            else:
                # Fallback: Wikipedia + DDG + SearXNG (free tier)
                batches = await asyncio.gather(
                    _wiki_search(q, req.limit),
                    _ddg_html_search(q, req.limit),
                    _searxng_search(q, req.limit),
                    _ddg_instant_search(q, req.limit),
                    return_exceptions=True,
                )
            seen_urls: set[str] = set()
            for batch in batches:
                if isinstance(batch, Exception):
                    continue
                for r in batch:
                    url = r.get('url', '')
                    if url and url not in seen_urls:
                        seen_urls.add(url)
                        results.append(r)
                    elif not url:
                        results.append(r)

    except Exception as e:
        return {'results': [], 'error': str(e)}

    return {'results': results[:req.limit]}


# ── Fetch page ─────────────────────────────────────────────────────────────────

@router.post('/api/fetch-page')
async def proxy_fetch_page(req: FetchPageRequest, role: AuthRole = Depends(require_role(AuthRole.MACHINE))):
    url = req.url.strip()
    if not url.startswith(('http://', 'https://')):
        raise HTTPException(400, detail={'error': 'url_invalido'})
    try:
        import httpx as _httpx_fp
        async with _httpx_fp.AsyncClient(timeout=12, follow_redirects=True) as _hc_fp:
            _r_fp = await _hc_fp.get(url, headers={
                'User-Agent':      'Mozilla/5.0 (compatible; AgenteAI/3.1; +https://github.com/Baida98/AI)',
                'Accept':          'text/html,application/xhtml+xml,*/*;q=0.8',
                'Accept-Language': 'it-IT,it;q=0.9,en;q=0.8',
            })
        raw_bytes = _r_fp.content[:500_000]
        try:
            raw = raw_bytes.decode('utf-8', errors='replace')
        except Exception:
            raw = raw_bytes.decode('latin-1', errors='replace')
        title, code_bks = _get_title(raw), _clean_html(raw)[1]
        text            = _clean_html(raw)[0]
        return {'url': url, 'title': title, 'text': text, 'code_blocks': code_bks}
    except Exception as e:
        return {'error': str(e), 'url': url, 'title': '', 'text': '', 'code_blocks': []}


# ── Analyze image ──────────────────────────────────────────────────────────────

@router.post('/api/analyze-image')
async def analyze_image(
    body: AnalyzeImageRequest, request: Request,
    role: AuthRole = Depends(require_role(AuthRole.MACHINE)),  # P19-SEC2-1: era fail-open
):
    """
    Vision AI — OpenRouter free VL models → Gemini fallback.
    [S191] rimossi modelli deprecated.
    [S-GAP23] X-Internal-Token guard — protegge consumi LLM da abusi esterni.
    """
    import re as _re2, json as _json
    from openai import OpenAI as _OAI

    VISION_MATRIX = []
    or_key  = os.getenv('OPENROUTER_API_KEY', '')
    or_base = 'https://openrouter.ai/api/v1'
    if or_key:
        for model in [
            'nvidia/nemotron-nano-12b-v2-vl:free',
            'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free',
        ]:
            VISION_MATRIX.append(('openrouter', or_key, or_base, model))

    gemini_key  = os.getenv('GEMINI_API_KEY') or os.getenv('GOOGLE_API_KEY', '')
    gemini_base = 'https://generativelanguage.googleapis.com/v1beta/openai/'
    if gemini_key:
        for model in [
            os.getenv('VISION_MODEL', ''),
            'gemini-2.5-flash',
            'gemini-2.0-flash',
            'gemini-2.0-flash-lite',
        ]:
            if model:
                VISION_MATRIX.append(('gemini', gemini_key, gemini_base, model))

    if not VISION_MATRIX:
        return {'ok': False, 'error': 'Nessun provider vision disponibile. Configura GEMINI_API_KEY o OPENROUTER_API_KEY.'}

    question = body.question or (
        "Analizza questa immagine. Rispondi in italiano con SOLO questo JSON valido:\n"
        "{\n"
        "  \"description\": \"descrizione breve e chiara (max 60 parole)\",\n"
        "  \"tags\": [\"tag1\", \"tag2\", \"tag3\"],\n"
        "  \"objects\": [\"oggetto1\", \"oggetto2\"],\n"
        "  \"text_in_image\": \"testo visibile nell'immagine, o null\",\n"
        "  \"mood\": \"atmosfera es: professionale, casual, naturale, vivace\"\n"
        "}\n"
        "Solo JSON. Nessun testo aggiuntivo prima o dopo."
    )

    messages = [{
        "role": "user",
        "content": [
            {"type": "text", "text": question},
            {"type": "image_url", "image_url": {"url": body.dataUrl, "detail": "low"}},
        ],
    }]

    last_err = None
    tried    = []

    for (pname, api_key, base_url, model) in VISION_MATRIX:
        try:
            vclient = _OAI(api_key=api_key, base_url=base_url)
            resp    = vclient.chat.completions.create(
                model=model, messages=messages, max_tokens=400, temperature=0.1,
            )
            raw = (resp.choices[0].message.content or "").strip()
            m   = _re2.search(r'\{[\s\S]*\}', raw)
            if m:
                try:
                    result = _json.loads(m.group())
                    return {
                        'ok':            True,
                        'description':   str(result.get('description', '')),
                        'tags':          list(result.get('tags', [])),
                        'objects':       list(result.get('objects', [])),
                        'text_in_image': result.get('text_in_image') or None,
                        'mood':          result.get('mood') or None,
                        'provider':      f'{pname}/{model}',
                        'filename':      body.filename,
                    }
                except _json.JSONDecodeError as _exc:
                    _logger.debug("[search] silenced %s", type(_exc).__name__)  # noqa: BLE001
            if raw:
                return {
                    'ok': True, 'description': raw[:300],  # S584: 250→300
                    'tags': [], 'objects': [], 'text_in_image': None, 'mood': None,
                    'provider': f'{pname}/{model}', 'filename': body.filename,
                }
        except Exception as exc:
            last_err = str(exc)
            tried.append(f'{pname}/{model}: {str(exc)[:200]}')  # S608: 60→200
            continue

    return {'ok': False, 'error': f'Tutti i provider vision falliti. Ultimo: {last_err}', 'tried': tried[:5]}