# Copyright 2026 SigmaSRC, Inc. All Rights Reserved.

"""Subtree 07 -- User activity indicators (Linux / Unix / macOS).

Best-effort, privacy-scoped detection of AI usage from user activity:
  - shell history showing AI CLI invocations or curl/wget to AI endpoints
  - browser AI web-app installs (PWA launchers / Chrome web-app bundles)

PRIVACY: this subtree is deliberately conservative. From shell history it
reports ONLY the matched AI marker token (e.g. "api.openai.com") and the
history file -- never the full command line, which could contain a pasted
API key. From browsers it reads only launcher/bundle metadata, never
profile content or history.

Read-only.
"""

from ai.common import vendor_for as _vendor_for
from ai.common import report_ai_finding as _report
from ai.common import is_unix as _is_unix

# Shell history files.
const HISTORY_FILES = {
    "/home/*/.bash_history", "/home/*/.zsh_history",
    "/home/*/.local/share/fish/fish_history", "/home/*/.histfile",
    "/root/.bash_history", "/root/.zsh_history",
    "/Users/*/.bash_history", "/Users/*/.zsh_history",
    "/Users/*/.local/share/fish/fish_history"
}

# Distinctive AI markers to look for in history (tokens + service domains).
const HISTORY_AI_MARKERS = {
    "api.openai.com", "chatgpt", "api.anthropic.com", "claude.ai",
    "generativelanguage.googleapis.com", "api.cohere.ai", "api.mistral.ai",
    "api.groq.com", "api.perplexity.ai", "api.x.ai", "openrouter.ai",
    "api.deepseek.com", "huggingface.co",
    "ollama", "aider", "sgpt", "huggingface-cli", "litellm"
}

# AI service domains for browser web-app detection.
const AI_DOMAINS = {
    "openai.com", "chatgpt.com", "claude.ai", "anthropic.com",
    "gemini.google.com", "bard.google.com", "perplexity.ai",
    "poe.com", "huggingface.co", "x.ai", "deepseek.com", "copilot.microsoft.com"
}

# Browser PWA launcher / web-app bundle locations.
const BROWSER_APP_LAUNCHERS = {
    "/home/*/.local/share/applications/chrome-*.desktop",
    "/home/*/.local/share/applications/*Chrome*.desktop",
    "/home/*/.local/share/applications/msedge-*.desktop"
}

const MACOS_CHROME_APPS = {
    "/Users/*/Applications/Chrome Apps.localized/*.app",
    "/Users/*/Applications/*.app",
    "/Users/*/Applications/Edge Apps.localized/*.app"
}


proc check_shell_history_ai(host: Host, approved_vendors: set of str = {}):
    """Scan shell history for AI CLI / endpoint usage. Reports the matched
    marker only, never the full command.
    """
    if not _is_unix(host):
        host.leave(0, "Shell-history check is Unix/macOS-only")
    let counter = host.integer()
    counter.setvalue(0)
    for pat in HISTORY_FILES:
        for f in host.glob({pat}):
            if f.exists and f.ftype == "file":
                let ef = host.editfile(f.filename)
                for m in HISTORY_AI_MARKERS:
                    let sel = concat(r".*", m)
                    let hits = ef.extract(sel, m)
                    if len(hits) > 0:
                        _report(host, approved_vendors, _vendor_for(m),
                                "AI usage in shell history",
                                concat(m, " in ", f.filename))
                        counter.setvalue(counter.getvalue() + 1)
    if counter.getvalue() == 0:
        host.compliance(0, "No AI usage found in shell history")


proc check_browser_ai_webapps(host: Host, approved_vendors: set of str = {}):
    """Detect installed AI web-apps via Chrome/Edge PWA launchers (Linux)
    and Chrome/Edge web-app bundles (macOS). Metadata only.
    """
    if not _is_unix(host):
        host.leave(0, "Browser web-app check is Unix/macOS-only")
    let counter = host.integer()
    counter.setvalue(0)
    # Linux: parse PWA .desktop launchers for AI domains in their Exec/URL.
    for pat in BROWSER_APP_LAUNCHERS:
        for f in host.glob({pat}):
            if f.exists and f.ftype == "file":
                let ef = host.editfile(f.filename)
                for d in AI_DOMAINS:
                    let hits = ef.extract(concat(r".*", d), d)
                    if len(hits) > 0:
                        _report(host, approved_vendors, _vendor_for(d),
                                "AI web-app installed (browser PWA)",
                                concat(d, " : ", f.filename))
                        counter.setvalue(counter.getvalue() + 1)
    # macOS: match Chrome/Edge web-app bundle names against AI markers.
    for pat in MACOS_CHROME_APPS:
        for f in host.glob({pat}):
            if f.exists:
                for d in AI_DOMAINS:
                    if find(lower(f.filename), d) >= 0:
                        _report(host, approved_vendors, _vendor_for(d),
                                "AI web-app installed (browser bundle)",
                                f.filename)
                        counter.setvalue(counter.getvalue() + 1)
    if counter.getvalue() == 0:
        host.compliance(0, "No AI web-apps detected in browser launchers")
