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
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
// SPF Smart Gateway - Reverse Proxy Browser Engine
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Reverse proxy web engine for agent browser interaction.
// SPF serves proxied pages on localhost with injected control JavaScript.
// Browser connects TO SPF via WebSocket — no ADB, no CDP, no Android socket isolation.
// All target URLs validated through web::validate_url() for SSRF protection.
//
// Architecture:
//   1. Agent calls spf_web_navigate(url)
//   2. Browser opens http://127.0.0.1:PORT/proxy?url=TARGET
//   3. http.rs route fetches page via ProxyEngine, injects control JS, serves it
//   4. Injected JS opens WebSocket to ws://127.0.0.1:PORT/ws/browser
//   5. Agent sends commands (click/fill/eval/etc) through BrowserSession → channel → WS → JS
//   6. JS executes commands, returns results via same path in reverse
//
// WB-2b: ProxyEngine + BrowserSession + data types
// WB-2c: Control JavaScript (CONTROL_JS const)

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::mpsc;
use std::time::Duration;

// ============================================================================
// PROXY ENGINE — Fetch pages, inject control JS, strip CSP
// ============================================================================

/// Reverse proxy engine — fetches external pages and prepares them for
/// local serving with injected control JavaScript.
pub struct ProxyEngine {
    client: reqwest::blocking::Client,
}

impl ProxyEngine {
    pub fn new() -> Result<Self, String> {
        let client = reqwest::blocking::Client::builder()
            .user_agent("Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36")
            .timeout(Duration::from_secs(30))
            .redirect(reqwest::redirect::Policy::limited(10))
            .build()
            .map_err(|e| format!("Failed to create proxy client: {}", e))?;
        Ok(Self { client })
    }

    /// Fetch a page, set `<base href>`, inject control JS, strip CSP.
    /// The `<base href>` tag makes the browser resolve all relative URLs
    /// (images, CSS, JS) against the original domain — no URL rewriting needed.
    pub fn proxy_page(&self, url: &str, ws_port: u16) -> Result<ProxiedPage, String> {
        crate::web::validate_url(url)?;

        let resp = self.client.get(url).send()
            .map_err(|e| format!("Proxy fetch failed: {}", e))?;

        if !resp.status().is_success() {
            return Err(format!("HTTP {}: {}", resp.status().as_u16(), url));
        }

        let content_type = resp.headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("text/html")
            .to_string();

        let body = resp.text()
            .map_err(|e| format!("Read body failed: {}", e))?;

        let title = extract_title(&body);

        // Non-HTML content — return as-is
        if !content_type.contains("html") && !body.trim_start().starts_with('<') {
            return Ok(ProxiedPage { html: body, content_type, title, original_url: url.to_string() });
        }

        let base_tag = format!("<base href=\"{}\">", html_escape(url));
        let control_js = control_script(ws_port);
        let mut html = body;

        // Insert <base> after <head>
        let lower = html.to_lowercase();
        if let Some(pos) = lower.find("<head>") {
            html.insert_str(pos + 6, &format!("\n{}\n", base_tag));
        } else if let Some(pos) = lower.find("<head ") {
            if let Some(close) = html[pos..].find('>') {
                html.insert_str(pos + close + 1, &format!("\n{}\n", base_tag));
            }
        } else if let Some(pos) = lower.find("<html") {
            if let Some(close) = html[pos..].find('>') {
                html.insert_str(pos + close + 1, &format!("\n<head>{}</head>\n", base_tag));
            }
        } else {
            html = format!("<head>{}</head>\n{}", base_tag, html);
        }

        // Insert control JS before </body>
        let lower = html.to_lowercase();
        if let Some(pos) = lower.rfind("</body>") {
            html.insert_str(pos, &control_js);
        } else {
            html.push_str(&control_js);
        }

        // Strip CSP meta tags that would block our injected JS
        html = strip_csp_meta(&html);

        Ok(ProxiedPage { html, content_type, title, original_url: url.to_string() })
    }

    /// Fetch a raw asset (CSS, JS, images) — passthrough proxy for pages
    /// that need cross-origin resources routed through localhost.
    pub fn proxy_asset(&self, url: &str) -> Result<AssetResponse, String> {
        crate::web::validate_url(url)?;

        let resp = self.client.get(url).send()
            .map_err(|e| format!("Asset fetch failed: {}", e))?;

        let content_type = resp.headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("application/octet-stream")
            .to_string();

        let data = resp.bytes()
            .map_err(|e| format!("Asset read failed: {}", e))?
            .to_vec();

        Ok(AssetResponse { data, content_type })
    }
}

/// Processed page ready for serving on localhost.
pub struct ProxiedPage {
    pub html: String,
    pub content_type: String,
    pub title: String,
    pub original_url: String,
}

/// Raw asset fetched for passthrough proxy.
pub struct AssetResponse {
    pub data: Vec<u8>,
    pub content_type: String,
}

// ============================================================================
// CHANNEL TYPES — Bridge between BrowserSession (sync) and WS handler (async)
// ============================================================================

/// Channel endpoints for the WebSocket handler in http.rs.
/// Created by BrowserSession::connect(), consumed by the /ws/browser handler.
/// Uses std::sync::mpsc — works across sync/async boundaries.
pub struct WsBrowserChannels {
    /// Receives commands from BrowserSession to forward to browser JS
    pub cmd_rx: mpsc::Receiver<String>,
    /// Sends responses from browser JS back to BrowserSession
    pub resp_tx: mpsc::Sender<String>,
}

// ============================================================================
// BROWSER SESSION — Stateful wrapper for MCP tool handlers
// ============================================================================

/// Persistent browser session for agent interaction.
/// Held in ServerState behind Mutex — same pattern as old CDP session.
/// Commands flow: session → cmd_tx → WS handler → browser JS
/// Responses flow: browser JS → WS handler → resp_tx → resp_rx → session
pub struct BrowserSession {
    engine: Option<ProxyEngine>,
    current_url: String,
    history: Vec<String>,
    screenshots_dir: String,
    screenshot_count: u32,
    proxy_port: u16,
    next_cmd_id: u32,
    cmd_tx: Option<mpsc::Sender<String>>,
    resp_rx: Option<mpsc::Receiver<String>>,
}

impl BrowserSession {
    pub fn new() -> Self {
        let screenshots_dir = format!(
            "{}/LIVE/TMP/screenshots",
            crate::paths::spf_root().display()
        );
        Self {
            engine: None,
            current_url: String::new(),
            history: Vec::new(),
            screenshots_dir,
            screenshot_count: 0,
            proxy_port: 0,
            next_cmd_id: 0,
            cmd_tx: None,
            resp_rx: None,
        }
    }

    /// Initialize proxy engine and create communication channels.
    /// Returns WsBrowserChannels for the http.rs WebSocket handler to consume.
    pub fn connect(&mut self, proxy_port: u16) -> Result<(String, WsBrowserChannels), String> {
        let engine = ProxyEngine::new()?;
        let (cmd_tx, cmd_rx) = mpsc::channel();
        let (resp_tx, resp_rx) = mpsc::channel();

        self.engine = Some(engine);
        self.cmd_tx = Some(cmd_tx);
        self.resp_rx = Some(resp_rx);
        self.proxy_port = proxy_port;
        self.next_cmd_id = 0;

        Ok((
            format!("Proxy engine ready on port {}. Browser tools active.", proxy_port),
            WsBrowserChannels { cmd_rx, resp_tx },
        ))
    }

    /// Navigate to URL — opens browser to proxied page, waits for WS connection.
    pub fn navigate(&mut self, url: &str) -> Result<String, String> {
        crate::web::validate_url(url)?;

        if self.engine.is_none() {
            return Err("Not connected. Run spf_web_connect first.".to_string());
        }

        if !self.current_url.is_empty() {
            self.history.push(self.current_url.clone());
        }
        self.current_url = url.to_string();

        // Build proxy URL for browser
        let proxy_url = format!(
            "http://127.0.0.1:{}/proxy?url={}",
            self.proxy_port,
            percent_encode(url),
        );

        // Open browser to proxy URL
        open_browser(&proxy_url)?;

        // Wait for control JS to connect and send "connected" message
        if let Some(ref resp_rx) = self.resp_rx {
            match resp_rx.recv_timeout(Duration::from_secs(15)) {
                Ok(msg) => {
                    let parsed: Value = serde_json::from_str(&msg).unwrap_or(json!({}));
                    let title = parsed.get("title").and_then(|v| v.as_str()).unwrap_or("");
                    Ok(format!("Navigated to: {} | Title: {}", url, title))
                }
                Err(_) => Ok(format!(
                    "Navigated to: {} | Browser opened (page may still be loading)", url
                )),
            }
        } else {
            Ok(format!("Navigated to: {} | No WebSocket channel", url))
        }
    }

    /// Send a command to browser JS and wait for matching response.
    fn send_command(&mut self, cmd: &str, extra: Value) -> Result<Value, String> {
        let cmd_tx = self.cmd_tx.as_ref()
            .ok_or("Not connected. Run spf_web_connect first.")?;
        let resp_rx = self.resp_rx.as_ref()
            .ok_or("Not connected. Run spf_web_connect first.")?;

        self.next_cmd_id += 1;
        let id = self.next_cmd_id;

        let mut msg = extra;
        if let Some(obj) = msg.as_object_mut() {
            obj.insert("id".to_string(), json!(id));
            obj.insert("cmd".to_string(), json!(cmd));
        }

        cmd_tx.send(msg.to_string())
            .map_err(|_| "Browser connection lost. Navigate to a page first.".to_string())?;

        // Wait for response with matching ID
        let deadline = std::time::Instant::now() + Duration::from_secs(15);
        loop {
            let remaining = deadline.saturating_duration_since(std::time::Instant::now());
            if remaining.is_zero() {
                return Err(format!("Timeout waiting for '{}' response", cmd));
            }

            match resp_rx.recv_timeout(remaining) {
                Ok(resp_str) => {
                    let parsed: Value = serde_json::from_str(&resp_str).unwrap_or(json!({}));
                    if parsed.get("id").and_then(|v| v.as_u64()) == Some(id as u64) {
                        let ok = parsed.get("ok").and_then(|v| v.as_bool()).unwrap_or(false);
                        let result = parsed.get("result").cloned().unwrap_or(json!(null));
                        return if ok { Ok(result) } else {
                            Err(result.as_str().unwrap_or("Command failed").to_string())
                        };
                    }
                    // Not our response — skip (could be "connected" event or stale)
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    return Err(format!("Timeout waiting for '{}' response", cmd));
                }
                Err(mpsc::RecvTimeoutError::Disconnected) => {
                    return Err("Browser connection lost".to_string());
                }
            }
        }
    }

    /// Click element by CSS selector.
    pub fn click(&mut self, selector: &str) -> Result<String, String> {
        let result = self.send_command("click", json!({"selector": selector}))?;
        Ok(result.as_str().unwrap_or("Clicked").to_string())
    }

    /// Fill form field by CSS selector.
    pub fn fill(&mut self, selector: &str, text: &str) -> Result<String, String> {
        let result = self.send_command("fill", json!({"selector": selector, "text": text}))?;
        Ok(result.as_str().unwrap_or("Filled").to_string())
    }

    /// Query elements by CSS selector.
    pub fn select(&mut self, selector: &str) -> Result<Vec<ElementInfo>, String> {
        let result = self.send_command("select", json!({"selector": selector}))?;
        serde_json::from_value(result)
            .map_err(|e| format!("Parse element info failed: {}", e))
    }

    /// Execute JavaScript on the current page.
    pub fn eval(&mut self, expression: &str) -> Result<Value, String> {
        self.send_command("eval", json!({"expression": expression}))
    }

    /// Get design brief from current page.
    pub fn design(&mut self) -> Result<DesignBrief, String> {
        let result = self.send_command("design", json!({}))?;
        serde_json::from_value(result)
            .map_err(|e| format!("Parse design brief failed: {}", e))
    }

    /// Capture DOM state and save as HTML file. Returns file path.
    pub fn screenshot(&mut self) -> Result<String, String> {
        let result = self.send_command("screenshot", json!({}))?;
        let html = result.get("html").and_then(|v| v.as_str()).unwrap_or("<html></html>");

        self.screenshot_count += 1;
        let path = format!("{}/screenshot_{}.html", self.screenshots_dir, self.screenshot_count);
        if let Some(parent) = std::path::Path::new(&path).parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        std::fs::write(&path, html)
            .map_err(|e| format!("Screenshot write failed: {}", e))?;
        Ok(path)
    }

    /// Get structured page overview (headings, forms, buttons, links, images).
    pub fn page_info(&mut self) -> Result<String, String> {
        let r = self.send_command("page", json!({}))?;

        let mut out = String::new();
        out.push_str(&format!("URL: {}\nTITLE: {}\n\n",
            r.get("url").and_then(|v| v.as_str()).unwrap_or(""),
            r.get("title").and_then(|v| v.as_str()).unwrap_or(""),
        ));

        if let Some(arr) = r.get("headings").and_then(|v| v.as_array()) {
            if !arr.is_empty() {
                out.push_str("=== HEADINGS ===\n");
                for h in arr {
                    out.push_str(&format!("[{}] {}\n",
                        h.get("tag").and_then(|v| v.as_str()).unwrap_or("?"),
                        h.get("text").and_then(|v| v.as_str()).unwrap_or(""),
                    ));
                }
                out.push('\n');
            }
        }

        if let Some(arr) = r.get("forms").and_then(|v| v.as_array()) {
            if !arr.is_empty() {
                out.push_str("=== FORMS ===\n");
                for (i, f) in arr.iter().enumerate() {
                    out.push_str(&format!("[FORM {}] {} {} ({} fields)\n", i,
                        f.get("method").and_then(|v| v.as_str()).unwrap_or("get").to_uppercase(),
                        f.get("action").and_then(|v| v.as_str()).unwrap_or(""),
                        f.get("fields").and_then(|v| v.as_u64()).unwrap_or(0),
                    ));
                }
                out.push('\n');
            }
        }

        if let Some(arr) = r.get("buttons").and_then(|v| v.as_array()) {
            if !arr.is_empty() {
                out.push_str("=== BUTTONS ===\n");
                for (i, b) in arr.iter().enumerate() {
                    out.push_str(&format!("[{}] {}\n", i,
                        b.get("text").and_then(|v| v.as_str()).unwrap_or(""),
                    ));
                }
                out.push('\n');
            }
        }

        if let Some(arr) = r.get("links").and_then(|v| v.as_array()) {
            if !arr.is_empty() {
                out.push_str("=== LINKS ===\n");
                for (i, l) in arr.iter().enumerate() {
                    out.push_str(&format!("[{}] \"{}\" -> {}\n", i,
                        l.get("text").and_then(|v| v.as_str()).unwrap_or(""),
                        l.get("href").and_then(|v| v.as_str()).unwrap_or(""),
                    ));
                }
                if let Some(total) = r.get("links_total").and_then(|v| v.as_u64()) {
                    out.push_str(&format!("... +{} more links\n", total - arr.len() as u64));
                }
                out.push('\n');
            }
        }

        if let Some(arr) = r.get("images").and_then(|v| v.as_array()) {
            if !arr.is_empty() {
                out.push_str("=== IMAGES ===\n");
                for (i, img) in arr.iter().enumerate() {
                    out.push_str(&format!("[{}] {} (alt: \"{}\")\n", i,
                        img.get("src").and_then(|v| v.as_str()).unwrap_or(""),
                        img.get("alt").and_then(|v| v.as_str()).unwrap_or(""),
                    ));
                }
                out.push('\n');
            }
        }

        if let Some(n) = r.get("element_count").and_then(|v| v.as_u64()) {
            out.push_str(&format!("Total elements: {}\n", n));
        }

        Ok(out)
    }

    /// Check if proxy engine is initialized.
    pub fn is_connected(&self) -> bool {
        self.engine.is_some()
    }

    /// Get current URL.
    /// Serve a proxied page — called by http.rs /proxy route handler.
    /// Returns None if proxy engine not initialised (spf_web_connect not called).
    pub fn proxy_page(&self, url: &str, ws_port: u16) -> Result<ProxiedPage, String> {
        match &self.engine {
            Some(engine) => engine.proxy_page(url, ws_port),
            None => Err("Browser not initialised. Call spf_web_connect first.".into()),
        }
    }

    /// Serve a proxied asset — called by http.rs /proxy/asset route handler.
    pub fn proxy_asset(&self, url: &str) -> Result<AssetResponse, String> {
        match &self.engine {
            Some(engine) => engine.proxy_asset(url),
            None => Err("Browser not initialised. Call spf_web_connect first.".into()),
        }
    }

    pub fn current_url(&self) -> &str {
        &self.current_url
    }

    /// Get ProxyEngine reference for http.rs route handler.
    pub fn engine(&self) -> Option<&ProxyEngine> {
        self.engine.as_ref()
    }
}

// ============================================================================
// DATA TYPES — Same API surface as old CDP module for MCP handler compat
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ElementInfo {
    pub tag: String,
    pub id: Option<String>,
    pub class: Option<String>,
    pub text: String,
    pub href: Option<String>,
    pub src: Option<String>,
    pub attributes: Vec<(String, String)>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DesignBrief {
    pub title: String,
    pub url: String,
    pub colors: Vec<String>,
    pub fonts: Vec<String>,
    pub body_font_size: String,
    pub body_line_height: String,
    pub container_width: String,
    pub components: Vec<ComponentInfo>,
    pub images: Vec<ImageInfo>,
    pub forms: Vec<FormInfo>,
    pub link_count: usize,
    pub script_count: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComponentInfo {
    pub component_type: String,
    pub index: usize,
    pub text: String,
    pub classes: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageInfo {
    pub src: String,
    pub alt: String,
    pub width: u32,
    pub height: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormInfo {
    pub action: String,
    pub method: String,
    pub fields: Vec<FieldInfo>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldInfo {
    pub name: String,
    pub field_type: String,
    pub required: bool,
}

// ============================================================================
// BROWSER LAUNCH — Platform-specific browser opener
// ============================================================================

/// Open URL in default browser. Android: am start. Linux: xdg-open.
#[cfg(target_os = "android")]
fn open_browser(url: &str) -> Result<(), String> {
    // Try Android activity manager first
    let am = std::process::Command::new("am")
        .args(["start", "-a", "android.intent.action.VIEW", "-d", url])
        .output();
    if let Ok(output) = am {
        if output.status.success() {
            return Ok(());
        }
    }
    // Fallback: termux-open-url (requires termux-api)
    let termux = std::process::Command::new("termux-open-url")
        .arg(url)
        .output();
    match termux {
        Ok(o) if o.status.success() => Ok(()),
        _ => Err("Failed to open browser. Ensure termux-api is installed.".to_string()),
    }
}

#[cfg(not(target_os = "android"))]
fn open_browser(url: &str) -> Result<(), String> {
    let result = std::process::Command::new("xdg-open").arg(url).output()
        .or_else(|_| std::process::Command::new("open").arg(url).output());
    match result {
        Ok(o) if o.status.success() => Ok(()),
        _ => Err("Failed to open browser".to_string()),
    }
}

// ============================================================================
// CONTROL JAVASCRIPT — Injected into proxied pages
// ============================================================================

/// Build the control script tag with the correct WebSocket port.
fn control_script(ws_port: u16) -> String {
    format!("\n<script>{}</script>\n", CONTROL_JS.replace("{WS_PORT}", &ws_port.to_string()))
}

/// Control JavaScript injected into every proxied page.
/// Opens WebSocket back to SPF, handles agent commands, intercepts navigation.
const CONTROL_JS: &str = r#"
(function(){
var ws=null,reconn=null;
function connect(){
 ws=new WebSocket('ws://127.0.0.1:{WS_PORT}/ws/browser');
 ws.onopen=function(){
  ws.send(JSON.stringify({type:'connected',url:location.href,title:document.title}));
 };
 ws.onmessage=function(e){
  try{var m=JSON.parse(e.data);handle(m);}catch(err){respond(0,false,err.toString());}
 };
 ws.onclose=function(){reconn=setTimeout(connect,2000);};
 ws.onerror=function(){};
}
function respond(id,ok,result){
 if(ws&&ws.readyState===1)ws.send(JSON.stringify({id:id,ok:ok,result:result}));
}
function handle(m){
 var id=m.id;
 try{
  switch(m.cmd){
   case 'click':cmdClick(id,m.selector);break;
   case 'fill':cmdFill(id,m.selector,m.text);break;
   case 'select':cmdSelect(id,m.selector);break;
   case 'eval':cmdEval(id,m.expression);break;
   case 'screenshot':cmdScreenshot(id);break;
   case 'design':cmdDesign(id);break;
   case 'page':cmdPage(id);break;
   default:respond(id,false,'Unknown command: '+m.cmd);
  }
 }catch(e){respond(id,false,e.toString());}
}
function cmdClick(id,sel){
 var el=document.querySelector(sel);
 if(!el){respond(id,false,'Element not found: '+sel);return;}
 var r=el.getBoundingClientRect();
 var x=r.left+r.width/2,y=r.top+r.height/2;
 el.dispatchEvent(new MouseEvent('mousedown',{bubbles:true,clientX:x,clientY:y}));
 el.dispatchEvent(new MouseEvent('mouseup',{bubbles:true,clientX:x,clientY:y}));
 el.dispatchEvent(new MouseEvent('click',{bubbles:true,clientX:x,clientY:y}));
 el.click();
 respond(id,true,'Clicked '+sel+' at ('+Math.round(x)+','+Math.round(y)+')');
}
function cmdFill(id,sel,text){
 var el=document.querySelector(sel);
 if(!el){respond(id,false,'Element not found: '+sel);return;}
 el.focus();el.value='';el.value=text;
 el.dispatchEvent(new Event('input',{bubbles:true}));
 el.dispatchEvent(new Event('change',{bubbles:true}));
 respond(id,true,'Filled '+sel+' with '+text.length+' chars');
}
function cmdSelect(id,sel){
 var els=document.querySelectorAll(sel);
 var out=[];
 for(var i=0;i<Math.min(els.length,100);i++){
  var el=els[i],attrs=[];
  for(var a=0;a<el.attributes.length;a++)
   attrs.push([el.attributes[a].name,el.attributes[a].value]);
  out.push({tag:el.tagName.toLowerCase(),id:el.id||null,
   class:el.className||null,text:(el.textContent||'').substring(0,200).trim(),
   href:el.getAttribute('href')||null,src:el.getAttribute('src')||null,
   attributes:attrs});
 }
 respond(id,true,out);
}
function cmdEval(id,expr){
 try{var r=eval(expr);respond(id,true,r);}
 catch(e){respond(id,false,'JS error: '+e.toString());}
}
function cmdScreenshot(id){
 respond(id,true,{type:'dom_capture',html:document.documentElement.outerHTML});
}
function cmdDesign(id){
 var bd=document.body,cs=getComputedStyle(bd);
 var colors={},fonts={};
 var all=document.querySelectorAll('*');
 for(var i=0;i<Math.min(all.length,500);i++){
  var s=getComputedStyle(all[i]);
  if(s.color&&s.color!=='rgba(0, 0, 0, 0)')colors[s.color]=(colors[s.color]||0)+1;
  if(s.backgroundColor&&s.backgroundColor!=='rgba(0, 0, 0, 0)')
   colors[s.backgroundColor]=(colors[s.backgroundColor]||0)+1;
  if(s.fontFamily)fonts[s.fontFamily]=(fonts[s.fontFamily]||0)+1;
 }
 var sc=Object.entries(colors).sort(function(a,b){return b[1]-a[1]}).slice(0,20).map(function(e){return e[0]});
 var sf=Object.entries(fonts).sort(function(a,b){return b[1]-a[1]}).slice(0,10).map(function(e){return e[0]});
 var comps=[];
 var tags=['nav','header','main','section','article','aside','footer','form'];
 for(var t=0;t<tags.length;t++){
  var te=document.querySelectorAll(tags[t]);
  for(var j=0;j<te.length;j++)
   comps.push({component_type:tags[t],index:j,
    text:(te[j].textContent||'').substring(0,100).trim(),classes:te[j].className||''});
 }
 var imgs=[];
 for(var k=0;k<Math.min(document.images.length,50);k++){
  var im=document.images[k];
  imgs.push({src:im.src,alt:im.alt||'',width:im.naturalWidth,height:im.naturalHeight});
 }
 var forms=[];
 for(var f=0;f<document.forms.length;f++){
  var flds=[];
  var fe=document.forms[f].elements;
  for(var e=0;e<fe.length;e++)
   if(fe[e].name)flds.push({name:fe[e].name,field_type:fe[e].type||'text',required:fe[e].required||false});
  forms.push({action:document.forms[f].action||'',method:document.forms[f].method||'get',fields:flds});
 }
 respond(id,true,{title:document.title||'',url:location.href,
  colors:sc,fonts:sf,body_font_size:cs.fontSize||'',body_line_height:cs.lineHeight||'',
  container_width:cs.maxWidth||'',components:comps,images:imgs,forms:forms,
  link_count:document.links.length,script_count:document.scripts.length});
}
function cmdPage(id){
 var hs=document.querySelectorAll('h1,h2,h3');
 var fs=document.querySelectorAll('form');
 var bs=document.querySelectorAll('button,input[type="submit"]');
 var ls=document.querySelectorAll('a[href]');
 var is=document.querySelectorAll('img');
 var r={url:location.href,title:document.title||'',
  headings:[],forms:[],buttons:[],links:[],images:[],
  element_count:document.querySelectorAll('*').length};
 for(var h=0;h<hs.length;h++)
  r.headings.push({tag:hs[h].tagName,text:hs[h].textContent.trim().substring(0,200)});
 for(var f=0;f<fs.length;f++)
  r.forms.push({action:fs[f].action,method:fs[f].method,fields:fs[f].elements.length});
 for(var b=0;b<bs.length;b++)
  r.buttons.push({text:(bs[b].textContent||bs[b].value||'').trim().substring(0,100)});
 var ml=Math.min(ls.length,30);
 for(var l=0;l<ml;l++)
  r.links.push({text:ls[l].textContent.trim().substring(0,100),href:ls[l].href});
 if(ls.length>ml)r.links_total=ls.length;
 var mi=Math.min(is.length,20);
 for(var i=0;i<mi;i++)
  r.images.push({src:is[i].src,alt:is[i].alt||''});
 if(is.length>mi)r.images_total=is.length;
 respond(id,true,r);
}
document.addEventListener('click',function(e){
 var t=e.target;
 while(t&&t.tagName!=='A')t=t.parentElement;
 if(t&&t.href&&t.href.indexOf('127.0.0.1')===-1){
  e.preventDefault();e.stopPropagation();
  window.location='/proxy?url='+encodeURIComponent(t.href);
 }
},true);
document.addEventListener('submit',function(e){
 var f=e.target;
 if(f.method&&f.method.toLowerCase()==='get'){
  e.preventDefault();
  var p=new URLSearchParams(new FormData(f)).toString();
  var a=f.action||location.href;
  window.location='/proxy?url='+encodeURIComponent(a+(a.indexOf('?')>=0?'&':'?')+p);
 }
},true);
connect();
})();
"#;

// ============================================================================
// HELPERS
// ============================================================================

/// Extract <title> from HTML string.
fn extract_title(html: &str) -> String {
    let lower = html.to_lowercase();
    if let Some(start) = lower.find("<title") {
        if let Some(open) = html[start..].find('>') {
            let after = start + open + 1;
            if let Some(end) = lower[after..].find("</title") {
                return html[after..after + end].trim().to_string();
            }
        }
    }
    String::new()
}

/// Escape HTML special characters for attribute values.
fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('"', "&quot;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

/// Strip Content-Security-Policy meta tags from HTML.
fn strip_csp_meta(html: &str) -> String {
    let mut result = html.to_string();
    let lower = result.to_lowercase();
    // Find and remove <meta http-equiv="content-security-policy" ...>
    let mut search_from = 0;
    loop {
        let search_lower = result[search_from..].to_lowercase();
        if let Some(pos) = search_lower.find("content-security-policy") {
            let abs_pos = search_from + pos;
            // Walk backward to find <meta
            let before = &result[..abs_pos].to_lowercase();
            if let Some(meta_start) = before.rfind("<meta") {
                // Walk forward to find >
                if let Some(end) = result[abs_pos..].find('>') {
                    let remove_end = abs_pos + end + 1;
                    result = format!("{}{}", &result[..meta_start], &result[remove_end..]);
                    search_from = meta_start;
                    continue;
                }
            }
            search_from = abs_pos + 23; // skip past this occurrence
        } else {
            break;
        }
    }
    let _ = lower; // suppress unused warning
    result
}

/// Percent-encode a URL for use as a query parameter value.
fn percent_encode(url: &str) -> String {
    let mut result = String::with_capacity(url.len() * 2);
    for byte in url.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9'
            | b'-' | b'_' | b'.' | b'~' => result.push(byte as char),
            _ => { result.push('%'); result.push_str(&format!("{:02X}", byte)); }
        }
    }
    result
}

/// Strip HTML tags from a string — simple text extraction.
pub fn strip_html_tags(html: &str) -> String {
    let mut result = String::new();
    let mut in_tag = false;
    for ch in html.chars() {
        match ch {
            '<' => in_tag = true,
            '>' => in_tag = false,
            _ if !in_tag => result.push(ch),
            _ => {}
        }
    }
    let mut collapsed = String::new();
    let mut prev_space = false;
    for ch in result.chars() {
        if ch.is_whitespace() {
            if !prev_space { collapsed.push(' '); prev_space = true; }
        } else {
            collapsed.push(ch); prev_space = false;
        }
    }
    collapsed.trim().to_string()
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_title() {
        assert_eq!(extract_title("<html><head><title>Hello World</title></head></html>"), "Hello World");
        assert_eq!(extract_title("<title>Test</title>"), "Test");
        assert_eq!(extract_title("<html>no title here</html>"), "");
        assert_eq!(extract_title("<head><title>  Trimmed  </title></head>"), "Trimmed");
    }

    #[test]
    fn test_html_escape() {
        assert_eq!(html_escape("https://example.com?a=1&b=2"), "https://example.com?a=1&amp;b=2");
        assert_eq!(html_escape("he said \"hi\""), "he said &quot;hi&quot;");
    }

    #[test]
    fn test_percent_encode() {
        assert_eq!(percent_encode("https://example.com/path"), "https%3A%2F%2Fexample.com%2Fpath");
        assert_eq!(percent_encode("hello world"), "hello%20world");
        assert_eq!(percent_encode("safe-chars_here.txt"), "safe-chars_here.txt");
    }

    #[test]
    fn test_strip_csp_meta() {
        let html = r#"<head><meta http-equiv="Content-Security-Policy" content="default-src 'self'"><title>Test</title></head>"#;
        let result = strip_csp_meta(html);
        assert!(!result.contains("Content-Security-Policy"));
        assert!(result.contains("<title>Test</title>"));
    }

    #[test]
    fn test_strip_csp_meta_preserves_other_meta() {
        let html = r#"<head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="x"><meta name="viewport" content="width=device-width"></head>"#;
        let result = strip_csp_meta(html);
        assert!(result.contains("charset"));
        assert!(result.contains("viewport"));
        assert!(!result.contains("Content-Security-Policy"));
    }

    #[test]
    fn test_strip_html_tags() {
        assert_eq!(strip_html_tags("<b>hello</b> world"), "hello world");
        assert_eq!(strip_html_tags("<div><p>nested</p></div>"), "nested");
        assert_eq!(strip_html_tags("no tags here"), "no tags here");
        assert_eq!(strip_html_tags("<a href=\"/test\">link text</a>"), "link text");
    }

    #[test]
    fn test_strip_html_tags_whitespace() {
        assert_eq!(strip_html_tags("<div>  hello   world  </div>"), "hello world");
        assert_eq!(strip_html_tags("<p>\n\n  text  \n</p>"), "text");
    }

    #[test]
    fn test_element_info_serialize() {
        let el = ElementInfo {
            tag: "a".to_string(),
            id: Some("link1".to_string()),
            class: Some("nav-link".to_string()),
            text: "Home".to_string(),
            href: Some("/".to_string()),
            src: None,
            attributes: vec![("href".to_string(), "/".to_string())],
        };
        let json = serde_json::to_string(&el).unwrap();
        assert!(json.contains("\"tag\":\"a\""));
        assert!(json.contains("\"text\":\"Home\""));
    }

    #[test]
    fn test_design_brief_deserialize() {
        let json = r#"{
            "title": "Test Page", "url": "https://example.com",
            "colors": ["rgb(0, 0, 0)"], "fonts": ["Arial"],
            "body_font_size": "16px", "body_line_height": "24px",
            "container_width": "1200px", "components": [],
            "images": [], "forms": [],
            "link_count": 5, "script_count": 2
        }"#;
        let brief: DesignBrief = serde_json::from_str(json).unwrap();
        assert_eq!(brief.title, "Test Page");
        assert_eq!(brief.link_count, 5);
    }

    #[test]
    fn test_browser_session_new() {
        let session = BrowserSession::new();
        assert!(!session.is_connected());
        assert!(session.current_url().is_empty());
    }

    #[test]
    fn test_control_script_port_injection() {
        let script = control_script(8080);
        assert!(script.contains("127.0.0.1:8080"));
        assert!(script.contains("<script>"));
        assert!(script.contains("</script>"));
        assert!(!script.contains("{WS_PORT}"));
    }
}