#!/usr/bin/env bash
# GuptAI — private local AI for Indian SMBs.
# Installs an open model via Ollama and drops a local web chat + India templates.
# Everything runs on THIS machine. Nothing is uploaded. https://gupt.aiskillhub.info
set -euo pipefail

BLUE='\033[0;34m'; GREEN='\033[0;32m'; YEL='\033[1;33m'; NC='\033[0m'
GUPT_HOME="${GUPT_HOME:-$HOME/.guptai}"
MODEL="${GUPT_MODEL:-llama3.2:3b}"
PORT="${GUPT_PORT:-8799}"

say()  { printf "${BLUE}» %s${NC}\n" "$1"; }
ok()   { printf "${GREEN}✓ %s${NC}\n" "$1"; }
warn() { printf "${YEL}! %s${NC}\n" "$1"; }

cat <<'BANNER'
   ____             _      _    ___
  / ___|_   _ _ __ | |_   / \  |_ _|
 | |  _| | | | '_ \| __| / _ \  | |
 | |_| | |_| | |_) | |_ / ___ \ | |
  \____|\__,_| .__/ \__/_/   \_\___|
             |_|   Private AI · your data never leaves this machine
BANNER

# 1. Ollama -------------------------------------------------------------------
if ! command -v ollama >/dev/null 2>&1; then
  say "Installing Ollama (the local model runtime)…"
  if [[ "$(uname)" == "Darwin" ]]; then
    warn "On macOS, download Ollama from https://ollama.com/download then re-run this script."
    exit 1
  fi
  curl -fsSL https://ollama.com/install.sh | sh
fi
ok "Ollama present: $(ollama --version 2>/dev/null || echo installed)"

# 2. Start the Ollama service -------------------------------------------------
if ! curl -fsS http://localhost:11434/api/tags >/dev/null 2>&1; then
  say "Starting Ollama service…"
  (ollama serve >/dev/null 2>&1 &) || true
  for i in $(seq 1 30); do
    curl -fsS http://localhost:11434/api/tags >/dev/null 2>&1 && break
    sleep 1
  done
fi
ok "Ollama service is running"

# 3. Pull the model -----------------------------------------------------------
say "Pulling model: $MODEL (one-time download)…"
ollama pull "$MODEL"
ok "Model ready: $MODEL"

# 4. Templates + local chat ---------------------------------------------------
mkdir -p "$GUPT_HOME/templates" "$GUPT_HOME/documents"

cat > "$GUPT_HOME/templates/law.txt" <<'EOF'
You are GuptAI for an Indian law firm. Draft legal notices, agreements and case
summaries in clear Indian legal English. Everything stays on this machine.
EOF
cat > "$GUPT_HOME/templates/clinic.txt" <<'EOF'
You are GuptAI for an Indian clinic. Summarise patient notes and draft discharge
summaries. Patient data never leaves this machine. Add a clinician-verify note.
EOF
cat > "$GUPT_HOME/templates/ca.txt" <<'EOF'
You are GuptAI for an Indian CA practice. Reply to GST notices, summarise ledgers
and answer questions over financial documents. Client financials stay on this machine.
EOF
ok "Template packs installed in $GUPT_HOME/templates"

# Minimal local chat page (talks to Ollama on localhost only)
cat > "$GUPT_HOME/chat.html" <<'EOF'
<!doctype html><html><head><meta charset="utf-8"><title>GuptAI — local</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>body{font-family:system-ui;max-width:760px;margin:2rem auto;padding:0 1rem;background:#0a0e17;color:#e7ecf3}
#log{min-height:50vh;white-space:pre-wrap}.u{color:#4f8dfb}.a{color:#2bd4a0}
input,button{font-size:16px;padding:.6rem;border-radius:.5rem;border:1px solid #1e2737;background:#111726;color:#e7ecf3}
form{display:flex;gap:.5rem;margin-top:1rem}#q{flex:1}</style></head><body>
<h2>🔒 GuptAI — running locally · nothing is uploaded</h2>
<div id="log"></div>
<form onsubmit="return ask(event)"><input id="q" placeholder="Ask anything…" autofocus><button>Send</button></form>
<script>
const M="__MODEL__";const log=document.getElementById('log');
async function ask(e){e.preventDefault();const q=document.getElementById('q');const t=q.value.trim();if(!t)return false;
log.innerHTML+=`\n<span class="u">You:</span> ${t}\n<span class="a">GuptAI:</span> `;q.value='';
const r=await fetch('http://localhost:11434/api/chat',{method:'POST',body:JSON.stringify({model:M,messages:[{role:'user',content:t}],stream:true})});
const rd=r.body.getReader(),dec=new TextDecoder();let buf='';
for(;;){const{done,value}=await rd.read();if(done)break;buf+=dec.decode(value,{stream:true});
const lines=buf.split('\n');buf=lines.pop();for(const l of lines){if(!l.trim())continue;try{const j=JSON.parse(l);if(j.message&&j.message.content){log.innerHTML+=j.message.content;window.scrollTo(0,document.body.scrollHeight);}}catch(_){}}}
return false;}
</script></body></html>
EOF
sed -i "s/__MODEL__/$MODEL/g" "$GUPT_HOME/chat.html" 2>/dev/null || \
  perl -pi -e "s/__MODEL__/$MODEL/g" "$GUPT_HOME/chat.html"
ok "Local chat UI written to $GUPT_HOME/chat.html"

# 5. Launcher -----------------------------------------------------------------
cat > "$GUPT_HOME/start.sh" <<EOF
#!/usr/bin/env bash
cd "$GUPT_HOME"
curl -fsS http://localhost:11434/api/tags >/dev/null 2>&1 || (ollama serve >/dev/null 2>&1 &)
echo "GuptAI chat → http://localhost:$PORT/chat.html"
python3 -m http.server $PORT
EOF
chmod +x "$GUPT_HOME/start.sh"

printf "\n"
ok "GuptAI installed."
printf "${GREEN}Start it any time:${NC}  bash %s/start.sh\n" "$GUPT_HOME"
printf "${GREEN}Then open:${NC}        http://localhost:%s/chat.html\n\n" "$PORT"
printf "Drop documents into %s/documents to reference them.\n" "$GUPT_HOME"
printf "Need help or RAG over your files? Managed plan → https://gupt.aiskillhub.info/pricing\n"
