#!/bin/bash

# CORES PARA O TERMINAL
VERDE='\033[0;32m'
CYAN='\033[0;36m'
VERMELHO='\033[0;31m'
AMARELO='\033[1;33m'
FIM='\033[0m'

clear
echo -e "${CYAN}====================================================${FIM}"
echo -e "${CYAN}   INSTALADOR AUTOMÁTICO - XTREAM IMPORTER V9 PRO   ${FIM}"
echo -e "${CYAN}====================================================${FIM}"
echo ""

# 1. ATUALIZAÇÃO E DEPENDÊNCIAS
echo -e "${AMARELO}[1/5] Atualizando sistema e instalando dependências...${FIM}"
sudo apt update -y > /dev/null 2>&1
sudo apt install python3 python3-pip ufw -y > /dev/null 2>&1

echo -e "${AMARELO}[2/5] Instalando bibliotecas Python (Streamlit, MySQL)...${FIM}"
pip3 install streamlit mysql-connector-python requests > /dev/null 2>&1
# Tenta instalar com break-system-packages caso seja Ubuntu 24+
pip3 install streamlit mysql-connector-python requests --break-system-packages > /dev/null 2>&1

# 2. LIMPEZA DE PROCESSOS ANTIGOS
echo -e "${AMARELO}[3/5] Limpando processos antigos...${FIM}"
pkill -f streamlit

# 3. CRIAÇÃO DO ARQUIVO PYTHON (V9 SECURE)
echo -e "${AMARELO}[4/5] Criando arquivo do Importador V9...${FIM}"

cat << 'EOF' > importer.py
import streamlit as st
import mysql.connector
import requests
import re
import json
import os
import time
from datetime import datetime

st.set_page_config(page_title="Xtream Admin V9", page_icon="🛡️", layout="wide")

CONFIG_FILE = "config.json"

def load_config():
    default_conf = {
        'env': 0, 'host': 'localhost', 'db': 'xtream_iptv', 'user': 'root', 'pass': '',
        'admin_user': 'admin', 'admin_pass': 'admin'
    }
    if os.path.exists(CONFIG_FILE):
        try:
            with open(CONFIG_FILE, "r") as f:
                data = json.load(f)
                for k, v in default_conf.items():
                    if k not in data: data[k] = v
                return data
        except: return default_conf
    return default_conf

def save_config(data):
    try:
        with open(CONFIG_FILE, "w") as f: json.dump(data, f)
    except: pass

config = load_config()

st.markdown("""
    <style>
    .stApp { background-color: #0f172a; }
    .stButton>button { 
        width: 100%; font-weight: bold; border-radius: 8px;
        background: linear-gradient(45deg, #3b82f6, #2563eb); 
        color: white; border: none; height: 45px;
    }
    .stButton>button:hover { background: linear-gradient(45deg, #2563eb, #1d4ed8); }
    .status-box { padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center; font-weight: bold; font-size: 1.1rem; }
    .online { background-color: #dcfce7; color: #14532d; border: 1px solid #22c55e; }
    .offline { background-color: #fee2e2; color: #7f1d1d; border: 1px solid #ef4444; }
    .login-container { padding: 2rem; border-radius: 15px; background: #1e293b; border: 1px solid #334155; text-align: center; }
    .login-title { color: #fff; font-size: 2rem; margin-bottom: 1rem; font-weight: 800; }
    </style>
""", unsafe_allow_html=True)

if 'logged_in' not in st.session_state: st.session_state['logged_in'] = False
if 'items' not in st.session_state: st.session_state['items'] = []
if 'cats' not in st.session_state: st.session_state['cats'] = []
if 'step' not in st.session_state: st.session_state['step'] = 1

if not st.session_state['logged_in']:
    c1, c2, c3 = st.columns([1,2,1])
    with c2:
        st.markdown("<br><br>", unsafe_allow_html=True)
        st.markdown('<div class="login-container"><div class="login-title">🚀 Xtream Admin</div><p style="color: #94a3b8;">Acesso Seguro V9</p></div>', unsafe_allow_html=True)
        with st.form("login_form"):
            u = st.text_input("Usuário")
            p = st.text_input("Senha", type="password")
            if st.form_submit_button("ENTRAR"):
                if u == config['admin_user'] and p == config['admin_pass']:
                    st.session_state['logged_in'] = True
                    st.success("Login realizado!"); time.sleep(0.5); st.rerun()
                else: st.error("Dados incorretos!")
    st.stop()

def get_conn(h, u, p, d):
    try: return mysql.connector.connect(host=h, user=u, password=p, database=d, connect_timeout=10)
    except: return None

def get_cat_id(cur, conn, name, ctype):
    if not name: name = "GERAL"
    cur.execute("SELECT id FROM stream_categories WHERE category_name=%s AND category_type=%s", (name, ctype))
    res = cur.fetchone()
    if res: return res[0]
    try:
        cur.execute("INSERT INTO stream_categories (category_type,category_name,parent_id) VALUES (%s,%s,0)", (ctype, name))
        conn.commit()
        return cur.lastrowid
    except: return 0

def get_data(conn, table, col_id, col_name):
    try:
        cur = conn.cursor(dictionary=True)
        cur.execute(f"SELECT {col_id}, {col_name} FROM {table}")
        return cur.fetchall()
    except: return []

def link_server(conn, s_ids, srv_id):
    if not s_ids: return
    try:
        cur = conn.cursor()
        vals = [(sid, srv_id) for sid in s_ids]
        cur.executemany("INSERT INTO streams_sys (stream_id, server_id, parent_id, on_demand) VALUES (%s, %s, 0, 0)", vals)
        conn.commit()
    except: pass

def update_bouquets(conn, s_ids, b_ids, ctype):
    if not s_ids or not b_ids: return
    cur = conn.cursor(dictionary=True)
    col = "bouquet_series" if ctype == "series" else "bouquet_channels"
    for bid in b_ids:
        cur.execute(f"SELECT {col} FROM bouquets WHERE id=%s", (bid,))
        row = cur.fetchone()
        curr = [] if not row or not row[col] else json.loads(row[col])
        if not isinstance(curr, list): curr = []
        final = list(set(curr + s_ids))
        cur.execute(f"UPDATE bouquets SET {col}=%s WHERE id=%s", (json.dumps(final), bid))
    conn.commit()

def process_m3u_stream(url):
    headers = {'User-Agent': 'Mozilla/5.0'}
    items = []; cats = set()
    rgx_grp = re.compile(r'group-title=["\']?([^"\',]+)["\']?')
    rgx_logo = re.compile(r'tvg-logo=["\']?([^"\']+)["\']?')
    status = st.empty()
    try:
        with requests.get(url, headers=headers, stream=True, timeout=120) as r:
            r.raise_for_status()
            curr_item = {}; count = 0
            for line in r.iter_lines():
                if not line: continue
                if isinstance(line, bytes): line = line.decode('utf-8', errors='ignore')
                line = line.strip()
                if line.startswith('#EXTINF'):
                    grp = rgx_grp.search(line)
                    logo = rgx_logo.search(line)
                    name = line.split(',')[-1].strip()
                    gname = grp.group(1) if grp else "GERAL"
                    curr_item = {'name': name, 'group': gname, 'logo': logo.group(1) if logo else "", 'url': ''}
                    cats.add(gname)
                elif not line.startswith('#') and curr_item:
                    curr_item['url'] = line
                    items.append(curr_item)
                    curr_item = {}; count += 1
                    if count % 1000 == 0: status.text(f"Lendo... {count} itens")
            status.success(f"Concluído! {count} itens."); return items, sorted(list(cats))
    except Exception as e: st.error(f"Erro: {e}"); return [], []

with st.sidebar:
    st.image("https://cdn-icons-png.flaticon.com/512/2920/2920349.png", width=50)
    st.header("Menu Admin")
    with st.expander("🔌 Conexão Database", expanded=True):
        denv = config.get('env', 0)
        etype = st.radio("Ambiente:", ["VPS/Dedicado", "Hospedagem"], index=0 if denv==0 else 1)
        host = st.text_input("Host", value=config.get('host', 'localhost'))
        dbname = st.text_input("Banco", value=config.get('db', 'xtream_iptv'))
        user = st.text_input("User", value=config.get('user', 'root'))
        pwd = st.text_input("Senha", value=config.get('pass', ''), type="password")
        if st.button("Salvar Conexão"):
            c = get_conn(host, user, pwd, dbname)
            if c:
                config.update({'env': 0 if etype=="VPS/Dedicado" else 1, 'host': host, 'db': dbname, 'user': user, 'pass': pwd})
                save_config(config); c.close(); st.success("Salvo!"); time.sleep(1); st.rerun()
            else: st.error("Erro ao conectar")
    with st.expander("🔐 Segurança"):
        na = st.text_input("Novo Usuário Admin")
        np = st.text_input("Nova Senha", type="password")
        if st.button("Atualizar Acesso"):
            if na and np:
                config['admin_user'] = na; config['admin_pass'] = np; save_config(config)
                st.success("Alterado!"); time.sleep(2); st.session_state['logged_in'] = False; st.rerun()
    if st.button("Sair"): st.session_state['logged_in'] = False; st.rerun()

st.title("Importador V9 (Secure)")
conn = get_conn(host, user, pwd, dbname)
if conn:
    st.markdown(f'<div class="status-box online">Conectado: {host}</div>', unsafe_allow_html=True)
    st.subheader("1. Fonte"); c1, c2 = st.columns([3,1])
    url = c1.text_input("URL M3U", disabled=st.session_state['step']>1)
    clabel = c2.selectbox("Tipo", ["Live (Canais)", "Movies (Filmes)", "Series"], disabled=st.session_state['step']>1)
    if st.session_state['step'] == 1 and st.button("ANALISAR LISTA"):
        if url:
            it, ct = process_m3u_stream(url)
            if it: st.session_state['items']=it; st.session_state['cats']=ct; st.session_state['step']=2; st.rerun()
    if st.session_state['step'] == 2:
        st.info(f"{len(st.session_state['items'])} itens."); r1 = st.columns(2)
        srvs = get_data(conn, 'streaming_servers', 'id', 'server_name')
        bqs = get_data(conn, 'bouquets', 'id', 'bouquet_name')
        sopts = {s['server_name']:s['id'] for s in srvs}; sname = r1[0].selectbox("Servidor:", list(sopts.keys()) if sopts else [])
        sid = sopts.get(sname)
        bopts = {b['bouquet_name']:b['id'] for b in bqs}; bnames = r1[1].multiselect("Pacotes:", list(bopts.keys()))
        bids = [bopts[x] for x in bnames]
        st.write("---"); cf = st.columns(3)
        if cf[0].button("Tudo"): st.session_state['sel_cats'] = st.session_state['cats']; st.rerun()
        if cf[1].button("Limpar"): st.session_state['sel_cats'] = []; st.rerun()
        if cf[2].button("Voltar"): st.session_state['step']=1; st.session_state['items']=[]; st.rerun()
        scats = st.multiselect("Categorias:", st.session_state['cats'], default=st.session_state.get('sel_cats',[]), key='cw')
        if st.button("🚀 IMPORTAR"):
            if not scats or not sid: st.error("Selecione Servidor e Categorias")
            else:
                iser = "Series" in clabel; imov = "Movies" in clabel
                tid = 5 if iser else (2 if imov else 1); cdb = "series" if iser else ("movie" if imov else "live")
                final = [i for i in st.session_state['items'] if i['group'] in scats]; tot = len(final)
                bar = st.progress(0); txt = st.empty(); cur = conn.cursor(); nids = []
                for i, item in enumerate(final):
                    try:
                        cid = get_cat_id(cur, conn, item['group'], cdb); ts = int(datetime.now().timestamp())
                        cur.execute("INSERT INTO streams (type, category_id, stream_display_name, stream_source, stream_icon, direct_source, added, enable_transcode, read_native) VALUES (%s,%s,%s,%s,%s,1,%s,0,1)", (tid, cid, item['name'], item['url'], item['logo'], ts))
                        nids.append(cur.lastrowid)
                    except: pass
                    if i%50==0: bar.progress((i+1)/tot); txt.text(f"Salvando {i}/{tot}...")
                conn.commit(); txt.text("Vinculando..."); link_server(conn, nids, sid); update_bouquets(conn, nids, bids, cdb)
                bar.progress(1.0); st.balloons(); st.success(f"{len(nids)} importados!"); time.sleep(2); st.session_state['step']=1; st.rerun()
else: st.markdown('<div class="status-box offline">Desconectado</div>', unsafe_allow_html=True)
EOF

# 4. EXECUÇÃO E PORTA
echo -e "${AMARELO}[5/5] Iniciando servidor e liberando porta 7001...${FIM}"
sudo ufw allow 7001/tcp > /dev/null 2>&1
nohup streamlit run importer.py --server.port 7001 --server.address 0.0.0.0 > output.log 2>&1 &

# 5. DADOS FINAIS
IP=$(curl -s ifconfig.me)
echo ""
echo -e "${VERDE}====================================================${FIM}"
echo -e "${VERDE}      INSTALAÇÃO CONCLUÍDA COM SUCESSO! 🚀        ${FIM}"
echo -e "${VERDE}====================================================${FIM}"
echo ""
echo -e "Acesse seu painel agora:"
echo -e "${CYAN}🔗 URL:${FIM}    http://$IP:7001"
echo -e "${CYAN}👤 Usuário:${FIM} admin"
echo -e "${CYAN}🔑 Senha:${FIM}   admin"
echo ""
echo -e "${AMARELO}NOTA: Altere a senha no menu 'Segurança' após entrar.${FIM}"
echo ""
