Skip to main content

atmos/os_lib/site_compat/
duckduckgo.rs

1// src/os_lib/web_engine/duckduckgo.rs - DuckDuckGo URL Parser, Result Parser & Lightweight Generator
2#![allow(dead_code)]
3
4extern crate alloc;
5use alloc::format;
6use alloc::string::{String, ToString};
7use alloc::vec::Vec;
8
9/// DuckDuckGo のフロントエンドバリアント
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum DuckDuckGoVariant {
12    /// 通常版 (duckduckgo.com)
13    Standard,
14    /// HTML 版 (html.duckduckgo.com/html/)
15    Html,
16    /// Lite 版 (lite.duckduckgo.com/lite/)
17    Lite,
18}
19
20impl DuckDuckGoVariant {
21    pub fn as_str(&self) -> &'static str {
22        match self {
23            DuckDuckGoVariant::Standard => "Standard",
24            DuckDuckGoVariant::Html => "HTML",
25            DuckDuckGoVariant::Lite => "Lite",
26        }
27    }
28
29    pub fn host(&self) -> &'static str {
30        match self {
31            DuckDuckGoVariant::Standard => "duckduckgo.com",
32            DuckDuckGoVariant::Html => "html.duckduckgo.com",
33            DuckDuckGoVariant::Lite => "lite.duckduckgo.com",
34        }
35    }
36
37    pub fn search_path(&self) -> &'static str {
38        match self {
39            DuckDuckGoVariant::Standard => "/",
40            DuckDuckGoVariant::Html => "/html/",
41            DuckDuckGoVariant::Lite => "/lite/",
42        }
43    }
44}
45
46/// DuckDuckGo の検索カテゴリ(タブ分類)
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum DuckDuckGoCategory {
49    /// すべて (通常の Web 検索)
50    Web,
51    /// 画像検索 (ia=images)
52    Images,
53    /// 動画検索 (ia=videos)
54    Videos,
55    /// ニュース検索 (ia=news)
56    News,
57}
58
59impl DuckDuckGoCategory {
60    pub fn as_str(&self) -> &'static str {
61        match self {
62            DuckDuckGoCategory::Web => "web",
63            DuckDuckGoCategory::Images => "images",
64            DuckDuckGoCategory::Videos => "videos",
65            DuckDuckGoCategory::News => "news",
66        }
67    }
68
69    pub fn from_ia_str(s: &str) -> Self {
70        let lower = s.to_ascii_lowercase();
71        match lower.as_str() {
72            "images" | "image" | "img" => DuckDuckGoCategory::Images,
73            "videos" | "video" | "vid" => DuckDuckGoCategory::Videos,
74            "news" | "article" => DuckDuckGoCategory::News,
75            _ => DuckDuckGoCategory::Web,
76        }
77    }
78
79    pub fn label(&self) -> &'static str {
80        match self {
81            DuckDuckGoCategory::Web => "すべて",
82            DuckDuckGoCategory::Images => "画像",
83            DuckDuckGoCategory::Videos => "動画",
84            DuckDuckGoCategory::News => "ニュース",
85        }
86    }
87
88    pub fn icon(&self) -> &'static str {
89        match self {
90            DuckDuckGoCategory::Web => "🔍",
91            DuckDuckGoCategory::Images => "🖼️",
92            DuckDuckGoCategory::Videos => "🎬",
93            DuckDuckGoCategory::News => "📰",
94        }
95    }
96}
97
98/// DuckDuckGo の URL 種別
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum DuckDuckGoUrlType {
101    /// トップページ
102    Home(DuckDuckGoVariant),
103    /// 検索結果ページ
104    Search {
105        query: String,
106        offset: usize,
107        variant: DuckDuckGoVariant,
108        category: DuckDuckGoCategory,
109    },
110    /// リダイレクトリンク (uddg トラッキングリンク)
111    Redirect {
112        target_url: String,
113    },
114}
115
116/// 検索結果 1 件
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct SearchResultItem {
119    /// ページのタイトル
120    pub title: String,
121    /// 遷移先の目的地 URL(uddg 解決済み)
122    pub target_url: String,
123    /// 画面に表示する短縮 URL
124    pub display_url: String,
125    /// 検索スニペット(概要テキスト)
126    pub snippet: String,
127}
128
129impl SearchResultItem {
130    /// 新規作成
131    pub fn new(title: String, target_url: String, display_url: String, snippet: String) -> Self {
132        Self {
133            title,
134            target_url,
135            display_url,
136            snippet,
137        }
138    }
139
140    /// ホスト名/ドメイン名を抽出(例: "rust-lang.org")
141    pub fn domain(&self) -> String {
142        let u = if !self.display_url.is_empty() {
143            &self.display_url
144        } else {
145            &self.target_url
146        };
147        let stripped = u
148            .strip_prefix("https://")
149            .or_else(|| u.strip_prefix("http://"))
150            .or_else(|| u.strip_prefix("//"))
151            .unwrap_or(u);
152        let host = stripped.split('/').next().unwrap_or(stripped);
153        let host = host.split('?').next().unwrap_or(host);
154        let host = host.strip_prefix("www.").unwrap_or(host);
155        host.to_string()
156    }
157
158    /// パンくずリスト形式に整形(例: "rust-lang.org › learn › get-started")
159    pub fn breadcrumb(&self) -> String {
160        let u = if !self.display_url.is_empty() {
161            &self.display_url
162        } else {
163            &self.target_url
164        };
165        let stripped = u
166            .strip_prefix("https://")
167            .or_else(|| u.strip_prefix("http://"))
168            .or_else(|| u.strip_prefix("//"))
169            .unwrap_or(u);
170        let mut parts = stripped.split('/').filter(|p| !p.is_empty());
171        let first = parts.next().unwrap_or("");
172        let domain = first.strip_prefix("www.").unwrap_or(first);
173        let mut bc = domain.to_string();
174        for p in parts.take(2) {
175            let clean_p = p.split('?').next().unwrap_or(p);
176            if !clean_p.is_empty() {
177                bc.push_str(" › ");
178                bc.push_str(clean_p);
179            }
180        }
181        if bc.is_empty() {
182            self.domain()
183        } else {
184            bc
185        }
186    }
187
188    /// ファビコン用の頭文字文字(英数字大文字)または地球アイコン
189    pub fn favicon_letter(&self) -> char {
190        let dom = self.domain();
191        dom.chars()
192            .find(|c| c.is_alphanumeric())
193            .map(|c| c.to_ascii_uppercase())
194            .unwrap_or('W')
195    }
196
197    /// HTTPS かどうか
198    pub fn is_https(&self) -> bool {
199        self.target_url.starts_with("https://") || self.target_url.starts_with("//")
200    }
201}
202
203/// 即時回答 / ナレッジパネル情報(Zero-click info / Instant Answer)
204#[derive(Debug, Clone, PartialEq, Eq)]
205pub struct InstantAnswer {
206    /// 見出し・タイトル
207    pub title: String,
208    /// 概要・定義テキスト
209    pub description: String,
210    /// 出典元 URL
211    pub source_url: Option<String>,
212    /// 出典元名称(例: "Wikipedia", "Official Docs")
213    pub source_name: Option<String>,
214    /// バッジラベル(例: "百科事典 / 百科辞書", "公式ガイド")
215    pub badge: String,
216}
217
218/// DuckDuckGo ページモデル(検索結果、即時回答、関連検索の統合)
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub struct DuckDuckGoPage {
221    /// 検索クエリ
222    pub query: String,
223    /// フロントエンドバリアント
224    pub variant: DuckDuckGoVariant,
225    /// ページネーションオフセット
226    pub offset: usize,
227    /// 検索カテゴリ (Web, Images, Videos, News)
228    pub category: DuckDuckGoCategory,
229    /// 即時回答 / ナレッジパネル(あれば)
230    pub instant_answer: Option<InstantAnswer>,
231    /// 検索結果リスト
232    pub results: Vec<SearchResultItem>,
233    /// 関連検索キーワード一覧
234    pub related_searches: Vec<String>,
235}
236
237/// ホスト名が DuckDuckGo 関連か判定
238// [S4-AUDIT: 要継続] 根拠: ホスト判定。サイト対応の入口。
239pub fn is_duckduckgo_host(host: &str) -> bool {
240    let h = host.to_ascii_lowercase();
241    let clean_h = h.split(':').next().unwrap_or(&h).trim();
242    clean_h == "duckduckgo.com"
243        || clean_h == "www.duckduckgo.com"
244        || clean_h == "lite.duckduckgo.com"
245        || clean_h == "html.duckduckgo.com"
246}
247
248/// URL デコード(パーセントエンコーディングおよび '+' を空白へ復元、UTF-8マルチバイト対応)
249// [S4-AUDIT: 要継続] 根拠: URL デコード。
250pub fn url_decode(s: &str) -> String {
251    let mut bytes_out = Vec::new();
252    let bytes = s.as_bytes();
253    let mut i = 0;
254    while i < bytes.len() {
255        if bytes[i] == b'%' && i + 2 < bytes.len() {
256            if let Ok(hex_str) = core::str::from_utf8(&bytes[i + 1..i + 3]) {
257                if let Ok(b) = u8::from_str_radix(hex_str, 16) {
258                    bytes_out.push(b);
259                    i += 3;
260                    continue;
261                }
262            }
263        } else if bytes[i] == b'+' {
264            bytes_out.push(b' ');
265            i += 1;
266            continue;
267        }
268        bytes_out.push(bytes[i]);
269        i += 1;
270    }
271    match String::from_utf8(bytes_out) {
272        Ok(s) => s,
273        Err(e) => {
274            let b = e.into_bytes();
275            let mut s = String::new();
276            for chunk in b.utf8_chunks() {
277                s.push_str(chunk.valid());
278            }
279            s
280        }
281    }
282}
283
284/// クエリ文字列または POST body から指定キーの値を取り出して URL デコードして返す
285// [S4-AUDIT: 要継続] 根拠: URL クエリ抽出。
286pub fn extract_query_param(query_or_body: &str, key: &str) -> Option<String> {
287    let clean = if let Some(idx) = query_or_body.find('?') {
288        query_or_body.get(idx + 1..).unwrap_or("")
289    } else {
290        query_or_body
291    };
292    for pair in clean.split('&') {
293        if pair.is_empty() {
294            continue;
295        }
296        let mut kv = pair.splitn(2, '=');
297        let k = kv.next().unwrap_or("");
298        let v = kv.next().unwrap_or("");
299        if k == key {
300            return Some(url_decode(v));
301        }
302    }
303    None
304}
305
306/// URL エンコード
307// [S4-AUDIT: 要継続] 根拠: URL エンコード(アドレス欄・検索で使用)。
308pub fn url_encode(s: &str) -> String {
309    let mut out = String::new();
310    for b in s.bytes() {
311        if b.is_ascii_lowercase()
312            || b.is_ascii_uppercase()
313            || b.is_ascii_digit()
314            || b == b'-'
315            || b == b'_'
316            || b == b'.'
317            || b == b'~'
318        {
319            out.push(b as char);
320        } else if b == b' ' {
321            out.push('+');
322        } else {
323            out.push_str(&format!("%{:02X}", b));
324        }
325    }
326    out
327}
328
329/// DuckDuckGo のトラッキングリダイレクト URL (`uddg=`) から正規の目的地 URL を抽出
330///
331/// 例:
332/// - `//duckduckgo.com/l/?uddg=https%3A%2F%2Fwww.rust-lang.org%2F&rut=...`
333///   -> `Some("https://www.rust-lang.org/")`
334/// - `/l/?uddg=https%3A%2F%2Fgithub.com%2F`
335///   -> `Some("https://github.com/")`
336// [S4-AUDIT: 要継続] 根拠: uddg リダイレクト解決。外部サイト独自形式。
337pub fn extract_direct_url_from_uddg(url: &str) -> Option<String> {
338    let clean = url.trim();
339    if !clean.contains("uddg=") {
340        return None;
341    }
342
343    let pos = clean.find("uddg=")?;
344    let after = clean.get(pos + 5..)?;
345    let raw_encoded = after.split('&').next().unwrap_or(after);
346    let decoded = url_decode(raw_encoded);
347    if decoded.starts_with("http://") || decoded.starts_with("https://") {
348        Some(decoded)
349    } else {
350        None
351    }
352}
353
354/// ホスト名から DuckDuckGo バリアントを判定
355// [S4-AUDIT: 要継続] 根拠: html/lite 等の亜種判定。
356pub fn detect_variant_from_host(host: &str) -> DuckDuckGoVariant {
357    let h = host.to_ascii_lowercase();
358    let clean_h = h.split(':').next().unwrap_or(&h).trim();
359    if clean_h.starts_with("lite.") {
360        DuckDuckGoVariant::Lite
361    } else if clean_h.starts_with("html.") {
362        DuckDuckGoVariant::Html
363    } else {
364        DuckDuckGoVariant::Standard
365    }
366}
367
368/// DuckDuckGo の URL を解析して URL 種別を返す
369// [S4-AUDIT: 要継続] 根拠: DDG URL 分類。軽量代替ページの入口。
370pub fn parse_duckduckgo_url(url: &str) -> Option<DuckDuckGoUrlType> {
371    let clean = url.trim();
372
373    // uddg リダイレクト
374    if let Some(target) = extract_direct_url_from_uddg(clean) {
375        return Some(DuckDuckGoUrlType::Redirect { target_url: target });
376    }
377
378    // ホスト名抽出
379    let without_scheme = clean
380        .strip_prefix("https://")
381        .or_else(|| clean.strip_prefix("http://"))
382        .or_else(|| clean.strip_prefix("//"))
383        .unwrap_or(clean);
384
385    let host = without_scheme.split('/').next().unwrap_or("");
386    if !is_duckduckgo_host(host) && !clean.starts_with('/') {
387        return None;
388    }
389
390    let variant = detect_variant_from_host(host);
391
392    // クエリ文字列の解析
393    let query_part = if let Some(q_idx) = clean.find('?') {
394        clean.get(q_idx + 1..).unwrap_or("")
395    } else {
396        ""
397    };
398
399    let mut query_val = None;
400    let mut offset_val = 0;
401    let mut category = DuckDuckGoCategory::Web;
402
403    for pair in query_part.split('&') {
404        if pair.is_empty() {
405            continue;
406        }
407        let mut kv = pair.splitn(2, '=');
408        let key = kv.next().unwrap_or("");
409        let val = kv.next().unwrap_or("");
410        if key == "q" {
411            query_val = Some(url_decode(val));
412        } else if key == "s" {
413            if let Ok(n) = val.parse::<usize>() {
414                offset_val = n;
415            }
416        } else if key == "ia" || key == "iar" {
417            category = DuckDuckGoCategory::from_ia_str(val);
418        }
419    }
420
421    if let Some(q) = query_val {
422        if !q.is_empty() {
423            return Some(DuckDuckGoUrlType::Search {
424                query: q,
425                offset: offset_val,
426                variant,
427                category,
428            });
429        }
430    }
431
432    Some(DuckDuckGoUrlType::Home(variant))
433}
434
435/// 検索クエリから DuckDuckGo URL を構築
436// [S4-AUDIT: 要継続] 根拠: 検索 URL 生成。
437pub fn build_duckduckgo_search_url(
438    query: &str,
439    variant: DuckDuckGoVariant,
440    offset: usize,
441    category: DuckDuckGoCategory,
442) -> String {
443    let enc_q = url_encode(query);
444    let base = format!("https://{}{}", variant.host(), variant.search_path());
445    let mut url = format!("{}?q={}", base, enc_q);
446    if category != DuckDuckGoCategory::Web {
447        url.push_str(&format!("&ia={}", category.as_str()));
448    }
449    if offset > 0 {
450        url.push_str(&format!("&s={}", offset));
451    }
452    url
453}
454
455/// HTML ソースから検索結果リストをパース抽出する純粋関数
456///
457/// 対応フォーマット:
458/// 1. DuckDuckGo Lite: `<td class="result-link"><a href="...">...</a></td>`
459/// 2. DuckDuckGo HTML: `<a class="result__url" href="...">...</a>` / `<div class="result ...">`
460/// 3. 汎用テーブル・リスト構造
461// [S4-AUDIT: 要QEMU検証] 根拠: 文字列走査による検索結果抽出。HTML5/DOM 準拠の改善で実ページ直接描画に置換できる見込み。実サイト確認が必要。
462pub fn parse_duckduckgo_results(html: &str) -> Vec<SearchResultItem> {
463    let mut results = Vec::new();
464    let lower = html.to_ascii_lowercase();
465
466    // 1. Lite 版の <table> ベースの結果パース
467    // 各結果は 通常 3 行(<tr>)に分かれている:
468    // (a) result-link (<a> タグ)
469    // (b) result-snippet
470    // (c) result-url
471    if lower.contains("result-link") || lower.contains("result-table") || lower.contains("result_link") {
472        let mut cur_pos = 0;
473        while let Some(a_idx) = html.get(cur_pos..).unwrap_or("").find("<a ") {
474            let abs_a = cur_pos + a_idx;
475            if let Some(close_tag) = html.get(abs_a..).unwrap_or("").find('>') {
476                let a_tag_open = html.get(abs_a..abs_a + close_tag + 1).unwrap_or("");
477                if a_tag_open.contains("result-link") || a_tag_open.contains("result_link") {
478                    if let Some(a_end) = html.get(abs_a..).unwrap_or("").find("</a>") {
479                        let a_full = html.get(abs_a..abs_a + a_end + 4).unwrap_or("");
480                        let href = extract_attribute_value(a_full, "href").unwrap_or_default();
481                        let title = strip_tags(a_full);
482                        let target_url = extract_direct_url_from_uddg(&href).unwrap_or(href.clone());
483
484                        // スニペットと表示 URL を探す
485                        let window_end = html.floor_char_boundary(abs_a + a_end + 1200);
486                        let snippet_window = html.get(abs_a + a_end..window_end).unwrap_or("");
487                        let mut snippet = String::new();
488                        if let Some(snip_idx) = snippet_window.find("result-snippet") {
489                            if let Some(td_start) = snippet_window.get(snip_idx..).unwrap_or("").find('>') {
490                                let content_start = snip_idx + td_start + 1;
491                                if let Some(td_end) = snippet_window.get(content_start..).unwrap_or("").find("</td>") {
492                                    snippet = strip_tags(snippet_window.get(content_start..content_start + td_end).unwrap_or(""));
493                                }
494                            }
495                        }
496
497                        let mut display_url = target_url.clone();
498                        if let Some(url_idx) = snippet_window.find("result-url") {
499                            if let Some(tag_start) = snippet_window.get(url_idx..).unwrap_or("").find('>') {
500                                let content_start = url_idx + tag_start + 1;
501                                if let Some(tag_end) = snippet_window.get(content_start..).unwrap_or("").find("</") {
502                                    let raw_u = strip_tags(snippet_window.get(content_start..content_start + tag_end).unwrap_or(""));
503                                    if !raw_u.is_empty() {
504                                        display_url = raw_u;
505                                    }
506                                }
507                            }
508                        }
509
510                        if !title.is_empty() && !target_url.is_empty() {
511                            results.push(SearchResultItem {
512                                title,
513                                target_url,
514                                display_url,
515                                snippet,
516                            });
517                        }
518
519                        cur_pos = abs_a + a_end + 4;
520                        continue;
521                    }
522                }
523            }
524            cur_pos = abs_a + 3;
525        }
526    }
527
528    // 2. HTML 版 (html.duckduckgo.com) のパース
529    if results.is_empty() && (lower.contains("result__title") || lower.contains("result__snippet") || lower.contains("result__url")) {
530        let mut cur_pos = 0;
531        while let Some(title_pos) = html.get(cur_pos..).unwrap_or("").find("result__title") {
532            let abs_pos = cur_pos + title_pos;
533            if let Some(a_start) = html.get(abs_pos..).unwrap_or("").find("<a ") {
534                let a_abs = abs_pos + a_start;
535                if let Some(a_end) = html.get(a_abs..).unwrap_or("").find("</a>") {
536                    let a_full = html.get(a_abs..a_abs + a_end + 4).unwrap_or("");
537                    let href = extract_attribute_value(a_full, "href").unwrap_or_default();
538                    let title = strip_tags(a_full);
539                    let target_url = extract_direct_url_from_uddg(&href).unwrap_or(href);
540
541                    let window = html.get(a_abs + a_end..html.floor_char_boundary(a_abs + a_end + 1200)).unwrap_or("");
542                    let mut snippet = String::new();
543                    if let Some(s_pos) = window.find("result__snippet") {
544                        if let Some(tag_end) = window.get(s_pos..).unwrap_or("").find('>') {
545                            let start = s_pos + tag_end + 1;
546                            if let Some(close) = window.get(start..).unwrap_or("").find("</") {
547                                snippet = strip_tags(window.get(start..start + close).unwrap_or(""));
548                            }
549                        }
550                    }
551
552                    let mut display_url = target_url.clone();
553                    if let Some(u_pos) = window.find("result__url") {
554                        if let Some(tag_end) = window.get(u_pos..).unwrap_or("").find('>') {
555                            let start = u_pos + tag_end + 1;
556                            if let Some(close) = window.get(start..).unwrap_or("").find("</") {
557                                let d = strip_tags(window.get(start..start + close).unwrap_or(""));
558                                if !d.is_empty() {
559                                    display_url = d;
560                                }
561                            }
562                        }
563                    }
564
565                    if !title.is_empty() && !target_url.is_empty() {
566                        results.push(SearchResultItem {
567                            title,
568                            target_url,
569                            display_url,
570                            snippet,
571                        });
572                    }
573
574                    cur_pos = a_abs + a_end + 4;
575                    continue;
576                }
577            }
578            cur_pos = abs_pos + 13;
579        }
580    }
581
582    // 3. 通常版 (duckduckgo.com: <article data-testid="result"> / data-result="snippet" / data-testid="result-title-a")
583    if results.is_empty() && (lower.contains("data-testid=\"result") || lower.contains("data-result=\"snippet") || lower.contains("<article")) {
584        let mut cur_pos = 0;
585        while let Some(article_start) = html.get(cur_pos..).unwrap_or("").find("<article") {
586            let abs_art = cur_pos + article_start;
587            let article_end = html.get(abs_art..).unwrap_or("").find("</article>").unwrap_or_else(|| html.floor_char_boundary(abs_art + 2500) - abs_art);
588            let art_str = html.get(abs_art..abs_art + article_end).unwrap_or("");
589
590            // タイトルとターゲット URL
591            let mut title = String::new();
592            let mut target_url = String::new();
593
594            // data-testid="result-title-a" を最優先、次に h2 内の <a>、最後に最初の <a>
595            let mut target_a_range = None;
596            if let Some(t_pos) = art_str.find("result-title-a") {
597                if let Some(prev_a) = art_str.get(..t_pos).unwrap_or("").rfind("<a ") {
598                    target_a_range = Some(prev_a);
599                }
600            }
601            if target_a_range.is_none() {
602                if let Some(h2_pos) = art_str.find("<h2") {
603                    if let Some(h2_a) = art_str.get(h2_pos..).unwrap_or("").find("<a ") {
604                        target_a_range = Some(h2_pos + h2_a);
605                    }
606                }
607            }
608            if target_a_range.is_none() {
609                target_a_range = art_str.find("<a ");
610            }
611
612            if let Some(a_start) = target_a_range {
613                if let Some(a_close) = art_str.get(a_start..).unwrap_or("").find("</a>") {
614                    let a_full = art_str.get(a_start..a_start + a_close + 4).unwrap_or("");
615                    let href = extract_attribute_value(a_full, "href").unwrap_or_default();
616                    title = strip_tags(a_full);
617                    target_url = extract_direct_url_from_uddg(&href).unwrap_or(href);
618                }
619            }
620
621            // スニペット: data-result="snippet" または class="...snippet..."
622            let mut snippet = String::new();
623            if let Some(snip_pos) = art_str.find("data-result=\"snippet\"").or_else(|| art_str.find("result-snippet")) {
624                if let Some(tag_end) = art_str.get(snip_pos..).unwrap_or("").find('>') {
625                    let start = snip_pos + tag_end + 1;
626                    if let Some(close) = art_str.get(start..).unwrap_or("").find("</") {
627                        snippet = strip_tags(art_str.get(start..start + close).unwrap_or(""));
628                    }
629                }
630            }
631
632            // 表示URL: data-testid="result-extras-url-link" または result-extras-url または target_url
633            let mut display_url = target_url.clone();
634            if let Some(url_pos) = art_str.find("result-extras-url") {
635                if let Some(tag_end) = art_str.get(url_pos..).unwrap_or("").find('>') {
636                    let start = url_pos + tag_end + 1;
637                    if let Some(close) = art_str.get(start..).unwrap_or("").find("</") {
638                        let d = strip_tags(art_str.get(start..start + close).unwrap_or(""));
639                        if !d.is_empty() {
640                            display_url = d;
641                        }
642                    }
643                }
644            }
645
646            if !title.is_empty() && !target_url.is_empty() {
647                results.push(SearchResultItem {
648                    title,
649                    target_url,
650                    display_url,
651                    snippet,
652                });
653            }
654
655            cur_pos = abs_art + article_end + 10;
656        }
657    }
658
659    results
660}
661
662/// HTML タグ属性値の抽出(例: `href="value"` や `href='value'`)
663// [S4-AUDIT: 要QEMU検証] 根拠: 文字列走査による属性抽出。HTML5 トークナイザ/DOM で代替できる見込み。確認が必要。
664fn extract_attribute_value(tag_str: &str, attr_name: &str) -> Option<String> {
665    let lower = tag_str.to_ascii_lowercase();
666    let pattern = format!("{}=", attr_name.to_ascii_lowercase());
667    let pos = lower.find(&pattern)?;
668    let after = tag_str.get(pos + pattern.len()..).unwrap_or("");
669
670    if after.starts_with('"') {
671        let end = after.get(1..).unwrap_or("").find('"')?;
672        Some(after.get(1..1 + end).unwrap_or("").to_string())
673    } else if after.starts_with('\'') {
674        let end = after.get(1..).unwrap_or("").find('\'')?;
675        Some(after.get(1..1 + end).unwrap_or("").to_string())
676    } else {
677        let end = after.find(&[' ', '>', '\t', '\r', '\n'][..]).unwrap_or(after.len());
678        Some(after.get(..end).unwrap_or("").to_string())
679    }
680}
681
682/// HTML タグを除去してテキストのみを抽出
683// [S4-AUDIT: 要QEMU検証] 根拠: タグ除去の自前実装。DOM の textContent で代替できる見込み。確認が必要。
684pub fn strip_tags(html: &str) -> String {
685    let mut out = String::new();
686    let mut inside_tag = false;
687    for c in html.chars() {
688        if c == '<' {
689            inside_tag = true;
690        } else if c == '>' {
691            inside_tag = false;
692        } else if !inside_tag {
693            out.push(c);
694        }
695    }
696    // HTML エンティティの簡易デコード
697    out.replace("&amp;", "&")
698        .replace("&lt;", "<")
699        .replace("&gt;", ">")
700        .replace("&quot;", "\"")
701        .replace("&#39;", "'")
702        .replace("&nbsp;", " ")
703        .trim()
704        .to_string()
705}
706
707/// クエリに応じた即時回答(ナレッジパネル)の生成(オフライン/シミュレーション用)
708// [S4-AUDIT: 要継続] 根拠: 即答カード(模擬)。軽量代替機能。
709pub fn get_instant_answer_for_query(query: &str) -> Option<InstantAnswer> {
710    let q = query.trim().to_ascii_lowercase();
711    if q.is_empty() {
712        return None;
713    }
714
715    if q.contains("rust") {
716        Some(InstantAnswer {
717            title: String::from("Rust (プログラミング言語)"),
718            description: String::from(
719                "Rust は、並行性、メモリ安全性、高パフォーマンスを重視して設計されたシステムプログラミング言語です。所有権モデルによりガベージコレクションなしでコンパイル時に安全性を保証します。",
720            ),
721            source_url: Some(String::from("https://www.rust-lang.org/")),
722            source_name: Some(String::from("Rust 公式サイト")),
723            badge: String::from("💡 プログラミング言語"),
724        })
725    } else if q.contains("atmos") {
726        Some(InstantAnswer {
727            title: String::from("AtmOS (Operating System)"),
728            description: String::from(
729                "AtmOS は ARM64 (Raspberry Pi 3B+ / 4) 向けに Rust でフルスクラッチ開発された次世代ベアメタル OS です。自前実装の Web エンジン、GUI、ネットワーク、USB スタックを搭載しています。",
730            ),
731            source_url: Some(String::from("https://github.com/sugi-lab/AtmOS")),
732            source_name: Some(String::from("AtmOS GitHub リポジトリ")),
733            badge: String::from("⚡ ベアメタル OS"),
734        })
735    } else if q.contains("raspberry pi") || q.contains("raspi") {
736        Some(InstantAnswer {
737            title: String::from("Raspberry Pi (シングルボードコンピュータ)"),
738            description: String::from(
739                "Raspberry Pi は、英国のラズベリーパイ財団によって開発されている教育・組み込み向けシングルボードコンピュータです。ARM アーキテクチャを採用しています。",
740            ),
741            source_url: Some(String::from("https://www.raspberrypi.com/")),
742            source_name: Some(String::from("Raspberry Pi Foundation")),
743            badge: String::from("🍓 ハードウェア / SBC"),
744        })
745    } else if q.contains("duckduckgo") || q.contains("ddg") {
746        Some(InstantAnswer {
747            title: String::from("DuckDuckGo (プライバシー保護検索エンジン)"),
748            description: String::from(
749                "DuckDuckGo は、ユーザーのプライバシー保護を最重視するインターネット検索エンジンです。検索履歴の保存や広告トラッカーによる追跡を行いません。",
750            ),
751            source_url: Some(String::from("https://duckduckgo.com/about")),
752            source_name: Some(String::from("DuckDuckGo About")),
753            badge: String::from("🦆 プライバシー検索"),
754        })
755    } else if q.contains("linux") {
756        Some(InstantAnswer {
757            title: String::from("Linux (OS カーネル)"),
758            description: String::from(
759                "Linux は、リーナス・トーバルズによって開発されたオープンソースのモノリシック Unix 系オペレーティングシステムカーネルです。世界中のサーバーや組み込み機器で稼働しています。",
760            ),
761            source_url: Some(String::from("https://kernel.org/")),
762            source_name: Some(String::from("The Linux Kernel Archives")),
763            badge: String::from("🐧 オープンソースカーネル"),
764        })
765    } else if q.contains("webassembly") || q.contains("wasm") {
766        Some(InstantAnswer {
767            title: String::from("WebAssembly (Wasm)"),
768            description: String::from(
769                "WebAssembly は、モダンな Web ブラウザ内でネイティブに近い高速性でコードを実行できるようにするスタックベースのバイナリ命令フォーマットです。",
770            ),
771            source_url: Some(String::from("https://webassembly.org/")),
772            source_name: Some(String::from("WebAssembly.org")),
773            badge: String::from("🌐 Web 標準技術"),
774        })
775    } else {
776        None
777    }
778}
779
780/// クエリに応じた関連検索キーワードの生成
781// [S4-AUDIT: 要継続] 根拠: 関連検索(模擬)。軽量代替機能。
782pub fn get_related_searches_for_query(query: &str) -> Vec<String> {
783    let q = query.trim();
784    if q.is_empty() {
785        return Vec::new();
786    }
787    let q_lower = q.to_ascii_lowercase();
788
789    if q_lower.contains("rust") {
790        alloc::vec![
791            String::from("Rust 入門"),
792            String::from("Rust cargo チュートリアル"),
793            String::from("Rust async/await"),
794            String::from("Rust embedded 組み込み"),
795            String::from("Rust WebAssembly"),
796        ]
797    } else if q_lower.contains("atmos") {
798        alloc::vec![
799            String::from("AtmOS WebEngine"),
800            String::from("AtmOS Raspberry Pi 3B+"),
801            String::from("自作 OS Rust"),
802            String::from("ARM64 bare-metal kernel"),
803        ]
804    } else if q_lower.contains("raspberry pi") || q_lower.contains("raspi") {
805        alloc::vec![
806            String::from("Raspberry Pi 3B+ 仕様"),
807            String::from("Raspberry Pi 4"),
808            String::from("Raspberry Pi OS"),
809            String::from("Raspberry Pi GPIO 制御"),
810        ]
811    } else if q_lower.contains("duckduckgo") {
812        alloc::vec![
813            String::from("DuckDuckGo プライバシー保護"),
814            String::from("DuckDuckGo 使い方"),
815            String::from("DuckDuckGo !bang 機能"),
816            String::from("DuckDuckGo Chromium 比較"),
817        ]
818    } else {
819        alloc::vec![
820            format!("{} 入門", q),
821            format!("{} とは", q),
822            format!("{} 使い方", q),
823            format!("{} 最新情報", q),
824        ]
825    }
826}
827
828/// HTML ソースから即時回答(Instant Answer / ナレッジパネル)をパース
829// [S4-AUDIT: 要QEMU検証] 根拠: 即答カードの文字列走査抽出。同上。
830pub fn parse_duckduckgo_instant_answer(html: &str) -> Option<InstantAnswer> {
831    let lower = html.to_ascii_lowercase();
832
833    let zci_marker = lower.find("zci-abstract")
834        .or_else(|| lower.find("class=\"zci"))
835        .or_else(|| lower.find("class=\"module--about"))
836        .or_else(|| lower.find("data-testid=\"about-item\""));
837
838    if let Some(pos) = zci_marker {
839        let window = html.get(pos..html.floor_char_boundary(pos + 2000)).unwrap_or("");
840        let mut title = String::new();
841        if let Some(h_start) = window.find("<h2").or_else(|| window.find("<h3")) {
842            if let Some(h_end) = window.get(h_start..).unwrap_or("").find("</h") {
843                title = strip_tags(window.get(h_start..h_start + h_end + 5).unwrap_or(""));
844            }
845        }
846        let mut desc = String::new();
847        if let Some(d_start) = window.find("zci__body").or_else(|| window.find("module__body")).or_else(|| window.find("<p")) {
848            if let Some(tag_close) = window.get(d_start..).unwrap_or("").find('>') {
849                let content_start = d_start + tag_close + 1;
850                if let Some(d_end) = window.get(content_start..).unwrap_or("").find("</") {
851                    desc = strip_tags(window.get(content_start..content_start + d_end).unwrap_or(""));
852                }
853            }
854        }
855        let mut src_url = None;
856        if let Some(a_pos) = window.find("<a ") {
857            if let Some(a_close) = window.get(a_pos..).unwrap_or("").find("</a>") {
858                let a_tag = window.get(a_pos..a_pos + a_close + 4).unwrap_or("");
859                if let Some(href) = extract_attribute_value(a_tag, "href") {
860                    let direct = extract_direct_url_from_uddg(&href).unwrap_or(href);
861                    src_url = Some(direct);
862                }
863            }
864        }
865
866        if !title.is_empty() && !desc.is_empty() {
867            return Some(InstantAnswer {
868                title,
869                description: desc,
870                source_url: src_url,
871                source_name: Some(String::from("DuckDuckGo Instant Answer")),
872                badge: String::from("💡 即時回答 / ナレッジ"),
873            });
874        }
875    }
876
877    None
878}
879
880/// HTML ソースから関連検索キーワードをパース
881// [S4-AUDIT: 要QEMU検証] 根拠: 関連検索の文字列走査抽出。同上。
882pub fn parse_duckduckgo_related_searches(html: &str) -> Vec<String> {
883    let mut related = Vec::new();
884    let lower = html.to_ascii_lowercase();
885
886    let marker = lower.find("related-searches")
887        .or_else(|| lower.find("data-testid=\"related-search\""))
888        .or_else(|| lower.find("class=\"js-related-searches"));
889
890    if let Some(pos) = marker {
891        let window = html.get(pos..html.floor_char_boundary(pos + 2500)).unwrap_or("");
892        let mut cur = 0;
893        while let Some(a_start) = window.get(cur..).unwrap_or("").find("<a ") {
894            let abs_a = cur + a_start;
895            if let Some(a_end) = window.get(abs_a..).unwrap_or("").find("</a>") {
896                let a_full = window.get(abs_a..abs_a + a_end + 4).unwrap_or("");
897                let text = strip_tags(a_full);
898                if !text.is_empty() && text.len() < 50 && !related.contains(&text) {
899                    related.push(text);
900                }
901                cur = abs_a + a_end + 4;
902            } else {
903                break;
904            }
905        }
906    }
907
908    related
909}
910
911/// カテゴリに応じたモック検索結果リストを生成(オフラインシミュレーション用)
912// [S4-AUDIT: 要継続] 根拠: オフライン/失敗時の模擬結果。軽量代替モード。
913pub fn get_mock_results_for_category(query: &str, category: DuckDuckGoCategory) -> Vec<SearchResultItem> {
914    let q_clean = query.trim();
915    let q_enc = url_encode(q_clean);
916    let q_lower = q_clean.to_ascii_lowercase();
917
918    match category {
919        DuckDuckGoCategory::Images => {
920            let mut items = Vec::new();
921            if q_lower.contains("rust") {
922                items.push(SearchResultItem::new(
923                    "Rust Logo - Official SVG Vector Artwork".to_string(),
924                    String::from("https://www.rust-lang.org/static/images/rust-logo-blk.svg"),
925                    String::from("rust-lang.org/static/images"),
926                    String::from("Official high-resolution black vector logo for the Rust programming language. Dimensions: 1920 × 1080"),
927                ));
928                items.push(SearchResultItem::new(
929                    "Ferris the Crab - Rust Community Mascot".to_string(),
930                    String::from("https://rustacean.net/assets/rustacean-flat-happy.svg"),
931                    String::from("rustacean.net"),
932                    String::from("Ferris the crab, the friendly and unofficial mascot of the Rust community. Dimensions: 1200 × 800"),
933                ));
934                items.push(SearchResultItem::new(
935                    "Rust Ownership & Borrowing Diagram".to_string(),
936                    String::from("https://doc.rust-lang.org/book/img/trpl04-01.png"),
937                    String::from("doc.rust-lang.org"),
938                    String::from("Visual memory layout showing stack and heap allocations with borrow checker invariants. Dimensions: 1440 × 900"),
939                ));
940                items.push(SearchResultItem::new(
941                    "Rust Compiler Architecture Overview".to_string(),
942                    String::from("https://rustc-dev-guide.rust-lang.org/img/rustc_driver.svg"),
943                    String::from("rustc-dev-guide.rust-lang.org"),
944                    String::from("Pipeline diagram of HIR, MIR, LLVM IR, and code generation phases in rustc. Dimensions: 1600 × 1200"),
945                ));
946            } else if q_lower.contains("raspberry") {
947                items.push(SearchResultItem::new(
948                    "Raspberry Pi 3 Model B+ Board Overview".to_string(),
949                    String::from("https://www.raspberrypi.com/products/raspberry-pi-3-model-b-plus/"),
950                    String::from("raspberrypi.com"),
951                    String::from("Quad-core 64-bit ARM Cortex-A53 SBC with gigabit Ethernet and dual-band WiFi. Dimensions: 1920 × 1080"),
952                ));
953                items.push(SearchResultItem::new(
954                    "Raspberry Pi 40-pin GPIO Pinout Diagram".to_string(),
955                    String::from("https://pinout.xyz/resources/raspberry-pi-pinout.png"),
956                    String::from("pinout.xyz"),
957                    String::from("Complete interactive pinout guide for UART, I2C, SPI, and PWM on Raspberry Pi. Dimensions: 1280 × 720"),
958                ));
959            } else {
960                items.push(SearchResultItem::new(
961                    format!("{} - High Resolution Concept Art & Preview", q_clean),
962                    format!("https://atmos.os/images/{}?format=svg", q_enc),
963                    format!("atmos.os/images/{}", q_enc),
964                    format!("Featured vector graphic and promotional concept art for {}. Dimensions: 1920 × 1080", q_clean),
965                ));
966                items.push(SearchResultItem::new(
967                    format!("{} - Architecture & Schematic Diagram", q_clean),
968                    format!("https://atmos.os/diagrams/{}?type=flow", q_enc),
969                    format!("atmos.os/diagrams/{}", q_enc),
970                    format!("Technical system flow and architectural breakdown for {}. Dimensions: 1600 × 900", q_clean),
971                ));
972                items.push(SearchResultItem::new(
973                    format!("{} - Interface & Component Screenshots", q_clean),
974                    format!("https://atmos.os/gallery/{}", q_enc),
975                    format!("atmos.os/gallery/{}", q_enc),
976                    format!("User interface mockups, rendering tests, and visual widgets for {}. Dimensions: 1280 × 720", q_clean),
977                ));
978            }
979            items
980        }
981        DuckDuckGoCategory::Videos => {
982            let mut items = Vec::new();
983            if q_lower.contains("rust") {
984                items.push(SearchResultItem::new(
985                    "Rust in 100 Seconds - Fast Overview".to_string(),
986                    String::from("https://www.youtube.com/watch?v=5C_HPTJg5Ek"),
987                    String::from("youtube.com/watch?v=5C_HPTJg5Ek"),
988                    String::from("A lightning-fast tour of Rust syntax, borrow checker, and zero-cost abstractions. Duration: 02:18"),
989                ));
990                items.push(SearchResultItem::new(
991                    "Writing a Bare-Metal OS in Rust from Scratch".to_string(),
992                    String::from("https://www.youtube.com/watch?v=atmos_os_guide"),
993                    String::from("youtube.com"),
994                    String::from("Complete architectural walkthrough of AtmOS: ARM64 MMU, SylFS, GUI, and web browser. Duration: 24:35"),
995                ));
996                items.push(SearchResultItem::new(
997                    "Rust Concurrency & Async Deep Dive".to_string(),
998                    String::from("https://www.youtube.com/watch?v=rust_async_2026"),
999                    String::from("youtube.com"),
1000                    String::from("Understanding Send/Sync traits, channels, and event loops in systems programming. Duration: 45:10"),
1001                ));
1002            } else {
1003                items.push(SearchResultItem::new(
1004                    format!("Introduction to {} - Getting Started Tutorial", q_clean),
1005                    format!("https://www.youtube.com/results?search_query={}", q_enc),
1006                    String::from("youtube.com"),
1007                    format!("Learn the basics, setup, and key features of {} in this comprehensive beginner guide. Duration: 15:42", q_clean),
1008                ));
1009                items.push(SearchResultItem::new(
1010                    format!("{} Advanced Architecture & Practical Examples", q_clean),
1011                    format!("https://www.youtube.com/watch?v=demo_{}", q_enc),
1012                    String::from("youtube.com"),
1013                    format!("Expert level design patterns, performance optimizations, and best practices for {}. Duration: 38:20", q_clean),
1014                ));
1015            }
1016            items
1017        }
1018        DuckDuckGoCategory::News => {
1019            let mut items = Vec::new();
1020            items.push(SearchResultItem::new(
1021                format!("{} Ecosystem Milestone & Major Update Released", q_clean),
1022                format!("https://atmos.os/news/{}", q_enc),
1023                "atmos.os/news".to_string(),
1024                format!("New release brings major performance breakthroughs, extended API compatibility, and enhanced developer tooling for {}. Published 2 hours ago.", q_clean),
1025            ));
1026            items.push(SearchResultItem::new(
1027                format!("Industry Trends: How {} is Modernizing Systems Software", q_clean),
1028                format!("https://techcrunch.com/topic/{}", q_enc),
1029                "techcrunch.com".to_string(),
1030                format!("Technology leaders and systems architects discuss how {} enables reliable, safe, and blazingly fast services. Published 6 hours ago.", q_clean),
1031            ));
1032            items.push(SearchResultItem::new(
1033                format!("Deep Dive into Bare-Metal Systems: Insights for {}", q_clean),
1034                format!("https://embedded.com/articles/{}", q_enc),
1035                "embedded.com".to_string(),
1036                "Technical report examining hardware isolation, deterministic execution, and kernel security models. Published 1 day ago.".to_string(),
1037            ));
1038            items
1039        }
1040        DuckDuckGoCategory::Web => {
1041            let mut results = alloc::vec![
1042                SearchResultItem::new(
1043                    alloc::format!("{} - AtmOS Knowledge Base", q_clean),
1044                    alloc::format!("https://atmos.os/search?q={}", q_enc),
1045                    alloc::format!("atmos.os/search?q={}", q_enc),
1046                    alloc::format!("Search results and complete documentation for '{}' running natively on the AtmOS WebEngine.", q_clean),
1047                ),
1048                SearchResultItem::new(
1049                    "DuckDuckGo Privacy Browser for AtmOS".to_string(),
1050                    String::from("https://duckduckgo.com/about"),
1051                    String::from("duckduckgo.com/about"),
1052                    String::from("DuckDuckGo is the search engine that protects your privacy. Fully optimized for lightweight embedded and OS-native browsers."),
1053                ),
1054                SearchResultItem::new(
1055                    "AtmOS Documentation & System Architecture".to_string(),
1056                    String::from("https://github.com/sugi-lab/AtmOS"),
1057                    String::from("github.com/sugi-lab/AtmOS"),
1058                    String::from("AtmOS is an ARM64-based bare-metal operating system featuring a high-performance web browser, GUI, and desktop environment."),
1059                ),
1060            ];
1061            if q_lower.contains("rust") {
1062                results.insert(0, SearchResultItem::new(
1063                    String::from("The Rust Programming Language"),
1064                    String::from("https://www.rust-lang.org/"),
1065                    String::from("rust-lang.org"),
1066                    String::from("A language empowering everyone to build reliable and efficient software. Fast, memory-safe, and highly concurrent."),
1067                ));
1068            } else if q_lower.contains("raspberry") {
1069                results.insert(0, SearchResultItem::new(
1070                    String::from("Raspberry Pi — Teach, learn, and make with Raspberry Pi"),
1071                    String::from("https://www.raspberrypi.com/"),
1072                    String::from("raspberrypi.com"),
1073                    String::from("The Raspberry Pi is a tiny and affordable computer that you can use to learn programming through fun, practical projects."),
1074                ));
1075            }
1076            results
1077        }
1078    }
1079}
1080
1081/// HTML ソースから DuckDuckGoPage モデル全体をパース構築
1082// [S4-AUDIT: 要QEMU検証] 根拠: 検索結果ページ再構築。実サイトを直接描画できれば不要。
1083pub fn parse_duckduckgo_page(
1084    html: &str,
1085    query: &str,
1086    variant: DuckDuckGoVariant,
1087    offset: usize,
1088    category: DuckDuckGoCategory,
1089) -> DuckDuckGoPage {
1090    let mut results = parse_duckduckgo_results(html);
1091    if results.is_empty() {
1092        results = get_mock_results_for_category(query, category);
1093    }
1094    let instant_answer = parse_duckduckgo_instant_answer(html)
1095        .or_else(|| get_instant_answer_for_query(query));
1096    let mut related_searches = parse_duckduckgo_related_searches(html);
1097    if related_searches.is_empty() {
1098        related_searches = get_related_searches_for_query(query);
1099    }
1100
1101    DuckDuckGoPage {
1102        query: String::from(query),
1103        variant,
1104        offset,
1105        category,
1106        instant_answer,
1107        results,
1108        related_searches,
1109    }
1110}
1111
1112/// DuckDuckGo ホーム画面の美麗 HTML を生成(AtmOS ブラウザ描画用)
1113// [S4-AUDIT: 要継続] 根拠: 軽量ホーム生成。フォールバックとして必要。
1114pub fn generate_duckduckgo_home_html(variant: DuckDuckGoVariant) -> String {
1115    let path = variant.search_path();
1116    let badge_html = match variant {
1117        DuckDuckGoVariant::Standard => String::new(),
1118        DuckDuckGoVariant::Html => String::from(r#"<span class="ddg-badge">HTML</span>"#),
1119        DuckDuckGoVariant::Lite => String::from(r#"<span class="ddg-badge">Lite</span>"#),
1120    };
1121
1122    format!(
1123        r#"<!DOCTYPE html>
1124<html>
1125<head>
1126<meta charset="utf-8">
1127<title>DuckDuckGo — プライバシー重視の検索エンジン (AtmOS)</title>
1128<style>
1129body {{
1130  background-color: #171821;
1131  color: #e6e8f0;
1132  font-family: sans-serif;
1133  margin: 0;
1134  padding: 0;
1135}}
1136.top-nav {{
1137  display: flex;
1138  justify-content: space-between;
1139  align-items: center;
1140  padding: 16px 28px;
1141  background-color: #1c1d28;
1142  border-bottom: 1px solid #292b3a;
1143}}
1144.nav-badge {{
1145  font-size: 13px;
1146  color: #45c486;
1147  background-color: #1a2c22;
1148  border: 1px solid #2a4c37;
1149  padding: 4px 10px;
1150  border-radius: 14px;
1151  font-weight: bold;
1152}}
1153.nav-links {{
1154  display: flex;
1155  gap: 16px;
1156}}
1157.nav-link {{
1158  color: #8c93a8;
1159  text-decoration: none;
1160  font-size: 13px;
1161}}
1162.ddg-container {{
1163  max-width: 720px;
1164  margin: 0 auto;
1165  padding: 50px 20px 40px;
1166  text-align: center;
1167}}
1168.ddg-emblem {{
1169  display: inline-block;
1170  font-size: 54px;
1171  line-height: 1;
1172  margin-bottom: 16px;
1173}}
1174.ddg-logo-text {{
1175  font-size: 42px;
1176  font-weight: bold;
1177  color: #de5833;
1178  letter-spacing: -0.5px;
1179  text-decoration: none;
1180  display: inline-block;
1181  margin-bottom: 8px;
1182}}
1183.ddg-badge {{
1184  font-size: 13px;
1185  color: #5c9df5;
1186  background-color: #262a3d;
1187  border: 1px solid #373e5a;
1188  padding: 3px 8px;
1189  border-radius: 6px;
1190  margin-left: 10px;
1191  vertical-align: middle;
1192}}
1193.ddg-tagline {{
1194  font-size: 16px;
1195  color: #a2a8bc;
1196  margin-bottom: 12px;
1197}}
1198.ddg-privacy-pills {{
1199  display: flex;
1200  justify-content: center;
1201  gap: 12px;
1202  margin-bottom: 32px;
1203}}
1204.privacy-pill {{
1205  font-size: 12px;
1206  color: #7d849a;
1207  background-color: #1e202c;
1208  padding: 4px 12px;
1209  border-radius: 12px;
1210  border: 1px solid #2a2d3e;
1211}}
1212.ddg-form {{
1213  display: flex;
1214  justify-content: center;
1215  align-items: center;
1216  margin-bottom: 28px;
1217  background-color: #212330;
1218  border: 2px solid #35384c;
1219  border-radius: 28px;
1220  padding: 4px 6px 4px 18px;
1221  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
1222}}
1223.search-icon {{
1224  font-size: 18px;
1225  color: #6c738c;
1226  margin-right: 12px;
1227}}
1228.ddg-input {{
1229  flex: 1;
1230  border: none;
1231  background: transparent;
1232  color: #ffffff;
1233  font-size: 16px;
1234  padding: 10px 0;
1235  outline: none;
1236}}
1237.ddg-btn {{
1238  padding: 10px 24px;
1239  font-size: 15px;
1240  font-weight: bold;
1241  border-radius: 22px;
1242  border: none;
1243  background-color: #de5833;
1244  color: #ffffff;
1245  cursor: pointer;
1246}}
1247.quick-tags {{
1248  margin-top: 10px;
1249  margin-bottom: 48px;
1250  font-size: 13px;
1251  color: #777e94;
1252}}
1253.tag-label {{
1254  margin-right: 8px;
1255}}
1256.tag-pill {{
1257  display: inline-block;
1258  color: #5c9df5;
1259  background-color: #1f2230;
1260  border: 1px solid #2e3347;
1261  padding: 4px 12px;
1262  border-radius: 14px;
1263  text-decoration: none;
1264  margin: 3px 5px;
1265  font-size: 13px;
1266}}
1267.features-grid {{
1268  display: flex;
1269  gap: 16px;
1270  text-align: left;
1271  margin-top: 30px;
1272  border-top: 1px solid #252736;
1273  padding-top: 36px;
1274}}
1275.feature-card {{
1276  flex: 1;
1277  background-color: #1f212c;
1278  border: 1px solid #2c2f3f;
1279  border-radius: 10px;
1280  padding: 18px 16px;
1281}}
1282.feature-icon {{
1283  font-size: 24px;
1284  margin-bottom: 10px;
1285}}
1286.feature-title {{
1287  font-size: 15px;
1288  font-weight: bold;
1289  color: #e0e3ee;
1290  margin-bottom: 6px;
1291}}
1292.feature-desc {{
1293  font-size: 12px;
1294  color: #8c92a6;
1295  line-height: 1.5;
1296}}
1297.ddg-footer {{
1298  margin-top: 50px;
1299  font-size: 12px;
1300  color: #5c6276;
1301}}
1302</style>
1303</head>
1304<body>
1305<div class="top-nav">
1306  <div class="nav-badge">🛡️ プライバシー保護作動中</div>
1307  <div class="nav-links">
1308    <a href="{action_path}" class="nav-link">ホーム</a>
1309    <a href="https://github.com/sugi-lab/AtmOS" class="nav-link">AtmOS WebEngine</a>
1310  </div>
1311</div>
1312
1313<div class="ddg-container">
1314  <div class="ddg-emblem">🦆</div>
1315  <div>
1316    <span class="ddg-logo-text">DuckDuckGo</span>
1317    {badge_html}
1318  </div>
1319  <div class="ddg-tagline">個人情報を追跡しない、次世代プライバシー保護検索</div>
1320  <div class="ddg-privacy-pills">
1321    <span class="privacy-pill">🔒 トラッカー追跡 0 件</span>
1322    <span class="privacy-pill">🕵️ 検索履歴非保持</span>
1323    <span class="privacy-pill">🛡️ 暗号化接続優先</span>
1324  </div>
1325
1326  <form action="{action_path}" method="get" class="ddg-form">
1327    <span class="search-icon">🔍</span>
1328    <input type="text" id="searchbox_input" name="q" class="ddg-input" placeholder="プライベートにウェブを検索..." autofocus autocomplete="off">
1329    <input type="submit" value="検索" class="ddg-btn">
1330  </form>
1331
1332  <div class="quick-tags">
1333    <span class="tag-label">クイック検索:</span>
1334    <a href="{action_path}?q=Rust+programming" class="tag-pill">🦀 Rust</a>
1335    <a href="{action_path}?q=Raspberry+Pi+3B" class="tag-pill">🍓 Raspberry Pi</a>
1336    <a href="{action_path}?q=AtmOS+Operating+System" class="tag-pill">⚡ AtmOS</a>
1337    <a href="{action_path}?q=Linux+kernel" class="tag-pill">🐧 Linux</a>
1338  </div>
1339
1340  <div class="features-grid">
1341    <div class="feature-card">
1342      <div class="feature-icon">🚫</div>
1343      <div class="feature-title">プライベート検索</div>
1344      <div class="feature-desc">検索履歴をサーバーに保存しません。誰にも覗かれない自由な検索環境を提供します。</div>
1345    </div>
1346    <div class="feature-card">
1347      <div class="feature-icon">🛡️</div>
1348      <div class="feature-title">トラッカー遮断</div>
1349      <div class="feature-desc">閲覧先サイトに潜む追跡広告やデータ収集スクリプトを先回りしてブロックします。</div>
1350    </div>
1351    <div class="feature-card">
1352      <div class="feature-icon">🔒</div>
1353      <div class="feature-title">スマート暗号化</div>
1354      <div class="feature-desc">暗号化されていない平文通信を可能な限り自動で安全な HTTPS 接続へ昇格させます。</div>
1355    </div>
1356  </div>
1357
1358  <div class="ddg-footer">
1359    AtmOS Bare-Metal WebEngine v1.0 • Raspberry Pi 3B+ / ARM64 • 2026
1360  </div>
1361</div>
1362</body>
1363</html>"#,
1364        badge_html = badge_html,
1365        action_path = path,
1366    )
1367}
1368
1369/// DuckDuckGoPage モデルから美麗な HTML 検索結果画面を生成
1370// [S4-AUDIT: 要継続] 根拠: 軽量検索結果ページ生成。同上。
1371pub fn generate_duckduckgo_page_html(page: &DuckDuckGoPage) -> String {
1372    let action_path = page.variant.search_path();
1373
1374    // 即時回答カード(あれば)
1375    let instant_answer_html = if let Some(ia) = &page.instant_answer {
1376        let src_btn = if let Some(url) = &ia.source_url {
1377            let name = ia.source_name.as_deref().unwrap_or("出典を見る");
1378            format!(
1379                r#"<div class="ia-action"><a href="{}" class="ia-link">{} ›</a></div>"#,
1380                url, name
1381            )
1382        } else {
1383            String::new()
1384        };
1385
1386        format!(
1387            r#"<div class="ia-card">
1388  <div class="ia-header">
1389    <span class="ia-badge">{}</span>
1390  </div>
1391  <div class="ia-title">{}</div>
1392  <div class="ia-desc">{}</div>
1393  {}
1394</div>"#,
1395            ia.badge, ia.title, ia.description, src_btn
1396        )
1397    } else {
1398        String::new()
1399    };
1400
1401    // 検索結果カードリスト(カテゴリ別特化レイアウト)
1402    let mut results_html = String::new();
1403    if page.results.is_empty() {
1404        results_html.push_str(r#"<div class="no-results">
1405  <div class="no-results-icon">🔍</div>
1406  <div class="no-results-title">検索結果が見つかりませんでした</div>
1407  <div class="no-results-desc">キーワードのスペルをご確認いただくか、より一般的な言葉をお試しください。</div>
1408</div>"#);
1409    } else {
1410        match page.category {
1411            DuckDuckGoCategory::Images => {
1412                results_html.push_str(r#"<div class="image-grid">"#);
1413                for item in &page.results {
1414                    let domain = item.domain();
1415                    results_html.push_str(&format!(
1416                        r#"<div class="image-card">
1417  <a href="{url}" class="image-thumb-box">
1418    <div class="image-thumb-placeholder">
1419      <span class="image-icon">🖼️</span>
1420      <span class="image-res-badge">HD</span>
1421    </div>
1422  </a>
1423  <div class="image-meta">
1424    <a href="{url}" class="image-title">{title}</a>
1425    <div class="image-domain">{domain}</div>
1426  </div>
1427</div>"#,
1428                        url = item.target_url,
1429                        title = item.title,
1430                        domain = domain,
1431                    ));
1432                }
1433                results_html.push_str("</div>");
1434            }
1435            DuckDuckGoCategory::Videos => {
1436                results_html.push_str(r#"<div class="video-grid">"#);
1437                for item in &page.results {
1438                    let domain = item.domain();
1439                    results_html.push_str(&format!(
1440                        r#"<div class="video-card">
1441  <a href="{url}" class="video-thumb-box">
1442    <div class="video-thumb-placeholder">
1443      <div class="video-play-icon">▶</div>
1444      <span class="video-duration-badge">HD</span>
1445    </div>
1446  </a>
1447  <div class="video-details">
1448    <a href="{url}" class="video-title">{title}</a>
1449    <div class="video-meta-bar">
1450      <span class="video-badge">🎬 動画</span>
1451      <span class="video-domain">{domain}</span>
1452    </div>
1453    <div class="video-snippet">{snippet}</div>
1454  </div>
1455</div>"#,
1456                        url = item.target_url,
1457                        title = item.title,
1458                        domain = domain,
1459                        snippet = item.snippet,
1460                    ));
1461                }
1462                results_html.push_str("</div>");
1463            }
1464            DuckDuckGoCategory::News => {
1465                results_html.push_str(r#"<div class="news-list">"#);
1466                for item in &page.results {
1467                    let domain = item.domain();
1468                    results_html.push_str(&format!(
1469                        r#"<div class="news-card">
1470  <div class="news-meta-row">
1471    <span class="news-source">{domain}</span>
1472    <span class="news-dot">•</span>
1473    <span class="news-time-badge">最新</span>
1474  </div>
1475  <a href="{url}" class="news-title">{title}</a>
1476  <div class="news-snippet">{snippet}</div>
1477</div>"#,
1478                        url = item.target_url,
1479                        title = item.title,
1480                        domain = domain,
1481                        snippet = item.snippet,
1482                    ));
1483                }
1484                results_html.push_str("</div>");
1485            }
1486            DuckDuckGoCategory::Web => {
1487                for (i, item) in page.results.iter().enumerate() {
1488                    let item_num = page.offset + i + 1;
1489                    let breadcrumb = item.breadcrumb();
1490                    let letter = item.favicon_letter();
1491                    let https_badge = if item.is_https() {
1492                        r#"<span class="https-tag">🔒</span>"#
1493                    } else {
1494                        ""
1495                    };
1496
1497                    results_html.push_str(&format!(
1498                        r#"<div class="result-card">
1499  <div class="result-domain-bar">
1500    <span class="favicon-badge">{letter}</span>
1501    <span class="breadcrumb-text">{breadcrumb}</span>
1502    {https_badge}
1503    <span class="result-num">#{num}</span>
1504  </div>
1505  <div class="result-title-row">
1506    <a href="{url}" class="result-title">{title}</a>
1507  </div>
1508  <div class="result-snippet">{snippet}</div>
1509</div>"#,
1510                        letter = letter,
1511                        breadcrumb = breadcrumb,
1512                        https_badge = https_badge,
1513                        num = item_num,
1514                        url = item.target_url,
1515                        title = item.title,
1516                        snippet = item.snippet,
1517                    ));
1518                }
1519            }
1520        }
1521    }
1522
1523    // 関連検索セクション
1524    let mut related_html = String::new();
1525    if !page.related_searches.is_empty() {
1526        let mut pills = String::new();
1527        let cat_suffix = if page.category != DuckDuckGoCategory::Web {
1528            format!("&ia={}", page.category.as_str())
1529        } else {
1530            String::new()
1531        };
1532        for r in &page.related_searches {
1533            pills.push_str(&format!(
1534                r#"<a href="{path}?q={q}{cat}" class="related-pill">🔍 {name}</a>"#,
1535                path = action_path,
1536                q = url_encode(r),
1537                cat = cat_suffix,
1538                name = r
1539            ));
1540        }
1541        related_html = format!(
1542            r#"<div class="related-box">
1543  <div class="related-title">関連する検索キーワード</div>
1544  <div class="related-pills">
1545    {}
1546  </div>
1547</div>"#,
1548            pills
1549        );
1550    }
1551
1552    // ページネーション
1553    let next_offset = page.offset + 30;
1554    let prev_offset = page.offset.saturating_sub(30);
1555    let cat_param = if page.category != DuckDuckGoCategory::Web {
1556        format!("&ia={}", page.category.as_str())
1557    } else {
1558        String::new()
1559    };
1560
1561    let mut pagination_html = String::new();
1562    if page.offset > 0 {
1563        pagination_html.push_str(&format!(
1564            r#"<a href="{path}?q={q}{cat}&s={prev}" class="page-btn">« 前の30件</a>"#,
1565            path = action_path,
1566            q = url_encode(&page.query),
1567            cat = cat_param,
1568            prev = prev_offset,
1569        ));
1570    }
1571    let cur_page = (page.offset / 30) + 1;
1572    pagination_html.push_str(&format!(
1573        r#"<span class="page-cur">ページ {}</span>"#,
1574        cur_page
1575    ));
1576    if !page.results.is_empty() {
1577        pagination_html.push_str(&format!(
1578            r#"<a href="{path}?q={q}{cat}&s={next}" class="page-btn">次の30件 »</a>"#,
1579            path = action_path,
1580            q = url_encode(&page.query),
1581            cat = cat_param,
1582            next = next_offset,
1583        ));
1584    }
1585
1586    let tab_web_class = if page.category == DuckDuckGoCategory::Web { "tab-item active" } else { "tab-item" };
1587    let tab_img_class = if page.category == DuckDuckGoCategory::Images { "tab-item active" } else { "tab-item" };
1588    let tab_vid_class = if page.category == DuckDuckGoCategory::Videos { "tab-item active" } else { "tab-item" };
1589    let tab_news_class = if page.category == DuckDuckGoCategory::News { "tab-item active" } else { "tab-item" };
1590
1591    let hidden_ia_input = if page.category != DuckDuckGoCategory::Web {
1592        format!(r#"<input type="hidden" name="ia" value="{}">"#, page.category.as_str())
1593    } else {
1594        String::new()
1595    };
1596
1597    format!(
1598        r#"<!DOCTYPE html>
1599<html>
1600<head>
1601<meta charset="utf-8">
1602<title>{query} - DuckDuckGo 検索 (AtmOS)</title>
1603<style>
1604body {{
1605  background-color: #171821;
1606  color: #e4e7f2;
1607  font-family: sans-serif;
1608  margin: 0;
1609  padding: 0;
1610}}
1611.header-bar {{
1612  background-color: #1c1d28;
1613  border-bottom: 1px solid #292c3a;
1614  padding: 12px 24px;
1615  display: flex;
1616  align-items: center;
1617  gap: 20px;
1618}}
1619.logo {{
1620  font-size: 20px;
1621  font-weight: bold;
1622  color: #de5833;
1623  text-decoration: none;
1624  white-space: nowrap;
1625}}
1626.search-form {{
1627  display: flex;
1628  flex: 1;
1629  max-width: 650px;
1630  background-color: #212330;
1631  border: 1px solid #36394c;
1632  border-radius: 22px;
1633  padding: 2px 4px 2px 14px;
1634  align-items: center;
1635}}
1636.search-input {{
1637  flex: 1;
1638  padding: 8px 4px;
1639  font-size: 15px;
1640  background: transparent;
1641  border: none;
1642  color: #ffffff;
1643  outline: none;
1644}}
1645.search-submit {{
1646  padding: 7px 18px;
1647  font-size: 14px;
1648  font-weight: bold;
1649  background-color: #de5833;
1650  border: none;
1651  border-radius: 18px;
1652  color: #ffffff;
1653  cursor: pointer;
1654}}
1655.header-shield {{
1656  font-size: 13px;
1657  color: #45c486;
1658  background-color: #1a2c22;
1659  border: 1px solid #2a4c37;
1660  padding: 4px 10px;
1661  border-radius: 12px;
1662  font-weight: bold;
1663  white-space: nowrap;
1664}}
1665.tabs-bar {{
1666  background-color: #191a24;
1667  border-bottom: 1px solid #262936;
1668  padding: 0 24px;
1669  display: flex;
1670  gap: 24px;
1671}}
1672.tab-item {{
1673  padding: 10px 4px;
1674  font-size: 14px;
1675  color: #8c93a8;
1676  text-decoration: none;
1677  border-bottom: 3px solid transparent;
1678}}
1679.tab-item.active {{
1680  color: #ffffff;
1681  font-weight: bold;
1682  border-bottom: 3px solid #de5833;
1683}}
1684.main-content {{
1685  max-width: 820px;
1686  margin: 0 auto;
1687  padding: 24px 20px 40px;
1688}}
1689.results-summary {{
1690  font-size: 13px;
1691  color: #7d849a;
1692  margin-bottom: 20px;
1693}}
1694.ia-card {{
1695  background-color: #1d2130;
1696  border: 1px solid #2c3348;
1697  border-left: 4px solid #5c9df5;
1698  border-radius: 10px;
1699  padding: 18px 22px;
1700  margin-bottom: 24px;
1701}}
1702.ia-header {{
1703  margin-bottom: 8px;
1704}}
1705.ia-badge {{
1706  font-size: 12px;
1707  font-weight: bold;
1708  color: #5c9df5;
1709  background-color: #1a283e;
1710  border: 1px solid #283e60;
1711  padding: 3px 8px;
1712  border-radius: 6px;
1713}}
1714.ia-title {{
1715  font-size: 20px;
1716  font-weight: bold;
1717  color: #ffffff;
1718  margin-bottom: 8px;
1719}}
1720.ia-desc {{
1721  font-size: 14px;
1722  line-height: 1.6;
1723  color: #c8cdda;
1724  margin-bottom: 12px;
1725}}
1726.ia-action {{
1727  text-align: right;
1728}}
1729.ia-link {{
1730  display: inline-block;
1731  font-size: 13px;
1732  color: #5c9df5;
1733  text-decoration: none;
1734  font-weight: bold;
1735}}
1736.result-card {{
1737  background-color: #1f212c;
1738  border: 1px solid #2b2e3e;
1739  border-radius: 10px;
1740  padding: 16px 20px;
1741  margin-bottom: 16px;
1742}}
1743.result-domain-bar {{
1744  display: flex;
1745  align-items: center;
1746  gap: 8px;
1747  margin-bottom: 6px;
1748}}
1749.favicon-badge {{
1750  display: inline-block;
1751  width: 20px;
1752  height: 20px;
1753  line-height: 20px;
1754  text-align: center;
1755  font-size: 11px;
1756  font-weight: bold;
1757  background-color: #2c3144;
1758  color: #5c9df5;
1759  border-radius: 4px;
1760}}
1761.breadcrumb-text {{
1762  font-size: 12px;
1763  color: #838a9e;
1764  word-break: break-all;
1765}}
1766.https-tag {{
1767  font-size: 11px;
1768}}
1769.result-num {{
1770  margin-left: auto;
1771  font-size: 11px;
1772  color: #575d70;
1773}}
1774.result-title-row {{
1775  margin-bottom: 6px;
1776}}
1777.result-title {{
1778  font-size: 18px;
1779  font-weight: bold;
1780  color: #5c9df5;
1781  text-decoration: none;
1782}}
1783.result-snippet {{
1784  font-size: 14px;
1785  line-height: 1.6;
1786  color: #c2c7d6;
1787}}
1788.related-box {{
1789  margin-top: 32px;
1790  background-color: #1b1c26;
1791  border: 1px solid #282a38;
1792  border-radius: 10px;
1793  padding: 18px 20px;
1794}}
1795.related-title {{
1796  font-size: 14px;
1797  font-weight: bold;
1798  color: #a0a6b8;
1799  margin-bottom: 12px;
1800}}
1801.related-pills {{
1802  display: flex;
1803  flex-wrap: wrap;
1804  gap: 10px;
1805}}
1806.related-pill {{
1807  display: inline-block;
1808  background-color: #222432;
1809  border: 1px solid #313548;
1810  color: #5c9df5;
1811  padding: 6px 14px;
1812  border-radius: 16px;
1813  font-size: 13px;
1814  text-decoration: none;
1815}}
1816.pagination {{
1817  display: flex;
1818  align-items: center;
1819  justify-content: center;
1820  gap: 16px;
1821  margin-top: 36px;
1822  padding-top: 24px;
1823  border-top: 1px solid #262936;
1824}}
1825.page-btn {{
1826  padding: 8px 18px;
1827  background-color: #212330;
1828  border: 1px solid #333648;
1829  border-radius: 8px;
1830  color: #5c9df5;
1831  text-decoration: none;
1832  font-size: 14px;
1833  font-weight: bold;
1834}}
1835.page-cur {{
1836  font-size: 13px;
1837  color: #7e859b;
1838}}
1839.no-results {{
1840  padding: 60px 20px;
1841  text-align: center;
1842}}
1843.no-results-icon {{
1844  font-size: 40px;
1845  margin-bottom: 16px;
1846}}
1847.no-results-title {{
1848  font-size: 18px;
1849  font-weight: bold;
1850  color: #d8dbe6;
1851  margin-bottom: 8px;
1852}}
1853.no-results-desc {{
1854  font-size: 14px;
1855  color: #7e859b;
1856}}
1857/* 画像検索特化グリッド */
1858.image-grid {{
1859  display: flex;
1860  flex-wrap: wrap;
1861  gap: 16px;
1862  margin-bottom: 24px;
1863}}
1864.image-card {{
1865  width: 230px;
1866  background-color: #1f212c;
1867  border: 1px solid #2b2e3e;
1868  border-radius: 10px;
1869  overflow: hidden;
1870  display: flex;
1871  flex-direction: column;
1872}}
1873.image-thumb-box {{
1874  display: block;
1875  text-decoration: none;
1876}}
1877.image-thumb-placeholder {{
1878  height: 130px;
1879  background-color: #242738;
1880  display: flex;
1881  align-items: center;
1882  justify-content: center;
1883  position: relative;
1884}}
1885.image-icon {{
1886  font-size: 32px;
1887}}
1888.image-res-badge {{
1889  position: absolute;
1890  bottom: 8px;
1891  right: 8px;
1892  background-color: #10121a;
1893  color: #a0a6b8;
1894  font-size: 10px;
1895  padding: 2px 6px;
1896  border-radius: 4px;
1897}}
1898.image-meta {{
1899  padding: 10px 12px;
1900  flex: 1;
1901}}
1902.image-title {{
1903  font-size: 13px;
1904  font-weight: bold;
1905  color: #5c9df5;
1906  text-decoration: none;
1907  display: block;
1908  margin-bottom: 4px;
1909}}
1910.image-domain {{
1911  font-size: 11px;
1912  color: #7d849a;
1913}}
1914/* 動画検索特化カード */
1915.video-grid {{
1916  display: flex;
1917  flex-direction: column;
1918  gap: 16px;
1919  margin-bottom: 24px;
1920}}
1921.video-card {{
1922  display: flex;
1923  gap: 16px;
1924  background-color: #1f212c;
1925  border: 1px solid #2b2e3e;
1926  border-radius: 10px;
1927  padding: 14px;
1928}}
1929.video-thumb-box {{
1930  text-decoration: none;
1931  flex-shrink: 0;
1932}}
1933.video-thumb-placeholder {{
1934  width: 180px;
1935  height: 105px;
1936  background-color: #202438;
1937  border-radius: 6px;
1938  display: flex;
1939  align-items: center;
1940  justify-content: center;
1941  position: relative;
1942}}
1943.video-play-icon {{
1944  font-size: 28px;
1945  color: #ff5555;
1946}}
1947.video-duration-badge {{
1948  position: absolute;
1949  bottom: 6px;
1950  right: 6px;
1951  background-color: #10121a;
1952  color: #ffffff;
1953  font-size: 11px;
1954  font-weight: bold;
1955  padding: 2px 6px;
1956  border-radius: 4px;
1957}}
1958.video-details {{
1959  flex: 1;
1960}}
1961.video-title {{
1962  font-size: 16px;
1963  font-weight: bold;
1964  color: #5c9df5;
1965  text-decoration: none;
1966  margin-bottom: 6px;
1967  display: block;
1968}}
1969.video-meta-bar {{
1970  display: flex;
1971  align-items: center;
1972  gap: 8px;
1973  margin-bottom: 8px;
1974}}
1975.video-badge {{
1976  font-size: 11px;
1977  color: #ff5555;
1978  background-color: #2e1d24;
1979  border: 1px solid #482631;
1980  padding: 2px 6px;
1981  border-radius: 4px;
1982}}
1983.video-domain {{
1984  font-size: 12px;
1985  color: #8c93a8;
1986}}
1987.video-snippet {{
1988  font-size: 13px;
1989  color: #c2c7d6;
1990  line-height: 1.5;
1991}}
1992/* ニュース特化カード */
1993.news-list {{
1994  display: flex;
1995  flex-direction: column;
1996  gap: 14px;
1997  margin-bottom: 24px;
1998}}
1999.news-card {{
2000  background-color: #1f212c;
2001  border: 1px solid #2b2e3e;
2002  border-radius: 10px;
2003  padding: 16px 20px;
2004}}
2005.news-meta-row {{
2006  display: flex;
2007  align-items: center;
2008  gap: 8px;
2009  margin-bottom: 6px;
2010}}
2011.news-source {{
2012  font-size: 12px;
2013  font-weight: bold;
2014  color: #f1fa8c;
2015}}
2016.news-dot {{
2017  color: #575d70;
2018  font-size: 12px;
2019}}
2020.news-time-badge {{
2021  font-size: 12px;
2022  color: #838a9e;
2023}}
2024.news-title {{
2025  font-size: 17px;
2026  font-weight: bold;
2027  color: #5c9df5;
2028  text-decoration: none;
2029  display: block;
2030  margin-bottom: 8px;
2031}}
2032.news-snippet {{
2033  font-size: 14px;
2034  color: #c2c7d6;
2035  line-height: 1.6;
2036}}
2037</style>
2038</head>
2039<body>
2040<div class="header-bar">
2041  <a href="{action_path}" class="logo">🦆 DuckDuckGo</a>
2042  <form action="{action_path}" method="get" class="search-form">
2043    <input type="text" name="q" value="{query}" class="search-input">
2044    {hidden_ia_input}
2045    <input type="submit" value="検索" class="search-submit">
2046  </form>
2047  <div class="header-shield">🛡️ 保護</div>
2048</div>
2049
2050<div class="tabs-bar">
2051  <a href="{action_path}?q={q_enc}" class="{tab_web_class}">🔍 すべて</a>
2052  <a href="{action_path}?q={q_enc}&ia=images" class="{tab_img_class}">🖼️ 画像</a>
2053  <a href="{action_path}?q={q_enc}&ia=videos" class="{tab_vid_class}">🎬 動画</a>
2054  <a href="{action_path}?q={q_enc}&ia=news" class="{tab_news_class}">📰 ニュース</a>
2055</div>
2056
2057<div class="main-content">
2058  <div class="results-summary">「{query}」の{category_label}検索結果</div>
2059  {instant_answer_html}
2060  {results_html}
2061  {related_html}
2062  <div class="pagination">
2063    {pagination_html}
2064  </div>
2065</div>
2066</body>
2067</html>"#,
2068        query = page.query,
2069        q_enc = url_encode(&page.query),
2070        action_path = action_path,
2071        category_label = page.category.label(),
2072        hidden_ia_input = hidden_ia_input,
2073        tab_web_class = tab_web_class,
2074        tab_img_class = tab_img_class,
2075        tab_vid_class = tab_vid_class,
2076        tab_news_class = tab_news_class,
2077        instant_answer_html = instant_answer_html,
2078        results_html = results_html,
2079        related_html = related_html,
2080        pagination_html = pagination_html,
2081    )
2082}
2083
2084/// DuckDuckGo 検索結果ページの軽量 HTML を生成(後方互換用ラッパー)
2085// [S4-AUDIT: 要継続] 根拠: 軽量結果一覧生成。同上。
2086pub fn generate_duckduckgo_results_html(
2087    query: &str,
2088    results: &[SearchResultItem],
2089    offset: usize,
2090    variant: DuckDuckGoVariant,
2091) -> String {
2092    let page = DuckDuckGoPage {
2093        query: String::from(query),
2094        variant,
2095        offset,
2096        category: DuckDuckGoCategory::Web,
2097        instant_answer: get_instant_answer_for_query(query),
2098        results: results.to_vec(),
2099        related_searches: get_related_searches_for_query(query),
2100    };
2101    generate_duckduckgo_page_html(&page)
2102}
2103
2104/// DuckDuckGo オートコンプリート API URL を構築
2105// [S4-AUDIT: 要継続] 根拠: オートコンプリート URL 生成。UI 機能。
2106pub fn build_autocomplete_url(query: &str) -> String {
2107    let enc_q = url_encode(query);
2108    format!("https://duckduckgo.com/ac/?q={}&type=list", enc_q)
2109}
2110
2111/// DuckDuckGo オートコンプリート JSON レスポンスをパースして候補リストを返す純粋関数
2112///
2113/// 対応フォーマット:
2114/// 1. `[{"phrase":"rust"},{"phrase":"rust programming"},...]`
2115/// 2. `["query",["rust","rust programming",...]]`
2116// [S4-AUDIT: 要継続] 根拠: オートコンプリート JSON 解析。UI 機能。
2117pub fn parse_autocomplete_results(json_str: &str) -> Vec<String> {
2118    let mut results = Vec::new();
2119    let trimmed = json_str.trim();
2120
2121    // 形式 1: phrase キー抽出
2122    if trimmed.contains("\"phrase\"") {
2123        let mut cur = 0;
2124        while let Some(idx) = trimmed.get(cur..).unwrap_or("").find("\"phrase\"") {
2125            let phrase_idx = cur + idx + 8; // past `"phrase"`
2126            if let Some(colon) = trimmed.get(phrase_idx..).unwrap_or("").find(':') {
2127                let after_colon = phrase_idx + colon + 1;
2128                if let Some(q_start) = trimmed.get(after_colon..).unwrap_or("").find('"') {
2129                    let str_start = after_colon + q_start + 1;
2130                    if let Some(q_end) = trimmed.get(str_start..).unwrap_or("").find('"') {
2131                        let phrase = trimmed.get(str_start..str_start + q_end).unwrap_or("");
2132                        let clean = phrase
2133                            .replace("\\\"", "\"")
2134                            .replace("\\\\", "\\")
2135                            .replace("\\/", "/");
2136                        if !clean.is_empty() && !results.contains(&clean) {
2137                            results.push(clean);
2138                        }
2139                        cur = str_start + q_end + 1;
2140                        continue;
2141                    }
2142                }
2143            }
2144            cur = phrase_idx;
2145        }
2146    } else if trimmed.starts_with('[') {
2147        // 形式 2: ["query", ["cand1", "cand2", ...]]
2148        // 2つ目のブラケット内を探す
2149        if let Some(second_open) = trimmed.find('[') {
2150            if let Some(inner_open) = trimmed.get(second_open + 1..).unwrap_or("").find('[') {
2151                let inner_start = second_open + 1 + inner_open + 1;
2152                if let Some(inner_close) = trimmed.get(inner_start..).unwrap_or("").find(']') {
2153                    let list_content = trimmed.get(inner_start..inner_start + inner_close).unwrap_or("");
2154                    let mut cur = 0;
2155                    while let Some(q1) = list_content.get(cur..).unwrap_or("").find('"') {
2156                        let s1 = cur + q1 + 1;
2157                        if let Some(q2) = list_content.get(s1..).unwrap_or("").find('"') {
2158                            let item = list_content.get(s1..s1 + q2).unwrap_or("");
2159                            let clean = item
2160                                .replace("\\\"", "\"")
2161                                .replace("\\\\", "\\")
2162                                .replace("\\/", "/");
2163                            if !clean.is_empty() && !results.contains(&clean) {
2164                                results.push(clean);
2165                            }
2166                            cur = s1 + q2 + 1;
2167                        } else {
2168                            break;
2169                        }
2170                    }
2171                }
2172            }
2173        }
2174    }
2175
2176    results
2177}
2178
2179/// オフライン環境・入力時即時サジェスト用の模擬補完候補
2180// [S4-AUDIT: 要継続] 根拠: 検索候補の模擬。UI 機能。
2181pub fn get_mock_suggestions(query: &str) -> Vec<String> {
2182    let q = query.trim().to_ascii_lowercase();
2183    if q.is_empty() {
2184        return Vec::new();
2185    }
2186
2187    // 組み込みの検索候補データベース
2188    static DICTIONARY: &[&str] = &[
2189        "rust",
2190        "rust programming",
2191        "rust compiler",
2192        "rust language",
2193        "rust cargo",
2194        "raspberry pi",
2195        "raspberry pi 3b",
2196        "raspberry pi kernel",
2197        "operating system",
2198        "os development",
2199        "os kernel",
2200        "atmos",
2201        "atmos operating system",
2202        "atmos web engine",
2203        "atmos browser",
2204        "duckduckgo",
2205        "duckduckgo search",
2206        "duckduckgo privacy",
2207        "duckduckgo lite",
2208        "youtube",
2209        "youtube music",
2210        "github",
2211        "kernel.org",
2212        "wikipedia",
2213        "arch linux",
2214        "arm64",
2215        "aarch64",
2216        "webassembly",
2217        "browser engine",
2218        "html5 specification",
2219        "css3 styling",
2220        "javascript engine",
2221        "検索",
2222        "検索エンジン",
2223        "研究室",
2224        "計算機科学",
2225    ];
2226
2227    let mut suggestions = Vec::new();
2228
2229    // 1. 完全一致・前方一致を優先
2230    for &word in DICTIONARY {
2231        let w_lower = word.to_ascii_lowercase();
2232        if w_lower.starts_with(&q) {
2233            suggestions.push(String::from(word));
2234        }
2235    }
2236
2237    // 2. 部分一致(前方一致で枠が余っている場合)
2238    if suggestions.len() < 6 {
2239        for &word in DICTIONARY {
2240            let w_lower = word.to_ascii_lowercase();
2241            if !w_lower.starts_with(&q) && w_lower.contains(&q)
2242                && !suggestions.iter().any(|s| s.eq_ignore_ascii_case(word)) {
2243                    suggestions.push(String::from(word));
2244                }
2245        }
2246    }
2247
2248    suggestions.truncate(6);
2249    suggestions
2250}