fenilsonani / menu-browser / Sources/ URLRuleManager.swift

import Foundation
import Combine
import os

private let log = Logger(subsystem: "com.fenilsonani.MenuBrowser", category: "URLRuleManager")

struct URLRule: Codable, Identifiable {
    let id: UUID
    var pattern: String          // domain or domain/path, e.g. "github.com/my-org"
    var browserBundleID: String
    var enabled: Bool
    var profileDirectory: String? // Chromium profile directory, e.g. "Profile 1"

    init(pattern: String, browserBundleID: String, profileDirectory: String? = nil) {
        self.id = UUID()
        self.pattern = pattern
        self.browserBundleID = browserBundleID
        self.enabled = true
        self.profileDirectory = profileDirectory
    }

    // Backwards compatibility
    enum CodingKeys: String, CodingKey {
        case id, pattern, browserBundleID, domain, enabled, profileDirectory
    }

    init(from decoder: Decoder) throws {
        let c = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try c.decode(UUID.self, forKey: .id)
        self.browserBundleID = try c.decode(String.self, forKey: .browserBundleID)
        self.enabled = (try? c.decode(Bool.self, forKey: .enabled)) ?? true
        self.profileDirectory = try? c.decode(String.self, forKey: .profileDirectory)
        if let p = try? c.decode(String.self, forKey: .pattern) {
            self.pattern = p
        } else {
            self.pattern = try c.decode(String.self, forKey: .domain)
        }
    }

    func encode(to encoder: Encoder) throws {
        var c = encoder.container(keyedBy: CodingKeys.self)
        try c.encode(id, forKey: .id)
        try c.encode(pattern, forKey: .pattern)
        try c.encode(browserBundleID, forKey: .browserBundleID)
        try c.encode(enabled, forKey: .enabled)
        try c.encodeIfPresent(profileDirectory, forKey: .profileDirectory)
    }
}

class URLRuleManager: ObservableObject {

    /// Storage keys owned by this manager. Exposed so tests can clear exactly what
    /// the manager writes instead of re-declaring the literals.
    enum DefaultsKey {
        static let rules = "urlRules"
        static let fallbackBrowser = "fallbackBrowserID"
        static let hitCounts = "ruleHitCounts"
    }

    private let defaults: UserDefaults

    @Published var rules: [URLRule] {
        didSet { rebuildSorted(); save() }
    }
    @Published var fallbackBrowserID: String? {
        didSet { defaults.set(fallbackBrowserID, forKey: DefaultsKey.fallbackBrowser) }
    }

    // Hit counts per rule ID
    private(set) var hitCounts: [String: Int] = [:] // UUID string → count

    // Pre-sorted rules for O(n) matching without per-call sort
    private var sortedRules: [URLRule] = []

    private func rebuildSorted() {
        sortedRules = rules.sorted { $0.pattern.count > $1.pattern.count }
    }

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
        if let data = defaults.data(forKey: DefaultsKey.rules),
           let decoded = try? JSONDecoder().decode([URLRule].self, from: data) {
            self.rules = decoded
        } else {
            self.rules = []
        }
        self.fallbackBrowserID = defaults.string(forKey: DefaultsKey.fallbackBrowser)
        self.hitCounts = (defaults.dictionary(forKey: DefaultsKey.hitCounts) as? [String: Int]) ?? [:]
        rebuildSorted()
    }

    private func saveHitCounts() {
        defaults.set(hitCounts, forKey: DefaultsKey.hitCounts)
    }

    func hitCount(for rule: URLRule) -> Int {
        hitCounts[rule.id.uuidString] ?? 0
    }

    private func recordHit(for rule: URLRule) {
        hitCounts[rule.id.uuidString, default: 0] += 1
        saveHitCounts()
    }

    private func save() {
        if let data = try? JSONEncoder().encode(rules) {
            defaults.set(data, forKey: DefaultsKey.rules)
        }
    }

    // MARK: - CRUD

    func addRule(pattern: String, browserBundleID: String, profileDirectory: String? = nil) {
        let cleaned = pattern
            .lowercased()
            .trimmingCharacters(in: .whitespacesAndNewlines)
            .replacingOccurrences(of: "https://", with: "")
            .replacingOccurrences(of: "http://", with: "")

        // Remove trailing slash but keep paths
        let trimmed = cleaned.hasSuffix("/") ? String(cleaned.dropLast()) : cleaned

        let rule = URLRule(pattern: trimmed, browserBundleID: browserBundleID, profileDirectory: profileDirectory)
        rules.append(rule)
        log.info("Added rule: \(trimmed) → \(browserBundleID)")
    }

    func deleteRule(id: UUID) {
        rules.removeAll { $0.id == id }
        hitCounts.removeValue(forKey: id.uuidString)
        saveHitCounts()
    }

    func toggleRule(id: UUID) {
        if let idx = rules.firstIndex(where: { $0.id == id }) {
            rules[idx].enabled.toggle()
        }
    }

    // MARK: - Matching

    /// Returns the bundle ID of the browser that should handle this URL,
    /// or nil if no rule matches (caller should use fallback).
    /// Supports domain-only patterns ("github.com") and domain+path patterns ("github.com/my-org").
    private func matchedRule(for url: URL) -> URLRule? {
        guard let host = url.host?.lowercased() else { return nil }
        let path = url.path.lowercased()
        let hostPath = host + path

        for rule in sortedRules {
            guard rule.enabled else { continue }
            let p = rule.pattern
            if p.contains("/") {
                if hostPath == p || hostPath.hasPrefix(p + "/") { return rule }
            } else {
                if host == p || host.hasSuffix("." + p) { return rule }
            }
        }
        return nil
    }

    /// Returns the matching rule for this URL, or nil if no rule matches.
    func matchingRule(for url: URL, recordHit: Bool = false) -> URLRule? {
        guard let rule = matchedRule(for: url) else { return nil }
        if recordHit {
            self.recordHit(for: rule)
            log.info("Rule matched: \(rule.pattern) → \(rule.browserBundleID)")
        }
        return rule
    }

    func matchingBrowser(for url: URL) -> String? {
        guard let rule = matchingRule(for: url, recordHit: true) else {
            let host = url.host?.lowercased() ?? "<unknown>"
            let path = url.path.lowercased()
            log.debug("No rule matched for \(host + path)")
            return nil
        }
        return rule.browserBundleID
    }
}