import os
import socket
import json
import sqlite3
from datetime import datetime
from flask import Flask, render_template_string, request, redirect, url_for, session
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text

# ================= CONFIGURAÇÕES =================
app = Flask(__name__)
app.secret_key = 'chave_mestra_segura_v4_fixed'
SENHA_MESTRA = "123"

# Caminho do banco de dados
basedir = os.path.abspath(os.path.dirname(__file__))
db_path = os.path.join(basedir, 'notas.db')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + db_path
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

# ================= CORREÇÃO AUTOMÁTICA DO BANCO =================
def corrigir_banco_de_dados():
    if not os.path.exists(db_path):
        return 

    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        try:
            cursor.execute("SELECT tipo FROM nota LIMIT 1")
        except sqlite3.OperationalError:
            print("⚠️ Atualizando banco de dados...")
            cursor.execute("ALTER TABLE nota ADD COLUMN tipo TEXT DEFAULT 'texto'")
            conn.commit()
            print("✅ Banco corrigido!")
        conn.close()
    except Exception as e:
        print(f"Erro ao verificar banco: {e}")

# ================= FRONT-END =================

HTML_LOGIN = """
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <style>
        body { background-color: #121212; color: #e0e0e0; font-family: sans-serif; display: flex; height: 100vh; align-items: center; justify-content: center; margin: 0; }
        .login-box { background: #1e1e1e; padding: 2rem; border-radius: 8px; width: 90%; max-width: 320px; text-align: center; box-shadow: 0 4px 10px rgba(0,0,0,0.5); }
        input { width: 100%; padding: 12px; margin: 10px 0; background: #2d2d2d; border: 1px solid #444; color: white; border-radius: 4px; box-sizing: border-box; font-size: 16px; }
        button { width: 100%; padding: 12px; background: #007acc; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; font-weight: bold; }
        .error { color: #ff5252; margin-top: 10px; font-size: 14px; }
    </style>
</head>
<body>
    <div class="login-box">
        <h2 style="margin-top:0; color:#007acc;">Code Vault</h2>
        <form method="POST">
            <input type="password" name="senha" placeholder="Senha de acesso" required autofocus>
            <button type="submit">Entrar</button>
        </form>
        {% if erro %} <div class="error">{{ erro }}</div> {% endif %}
    </div>
</body>
</html>
"""

HTML_INDEX = """
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Code Vault</title>
    <style>
        :root { --bg: #121212; --sidebar-bg: #1e1e1e; --border: #333; --accent: #007acc; --text: #e0e0e0; --success: #2ea043; }
        * { box-sizing: border-box; }
        body { margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: var(--bg); color: var(--text); height: 100vh; overflow: hidden; display: flex; flex-direction: column; }

        header { height: 50px; background: var(--sidebar-bg); border-bottom: 1px solid var(--border); display: flex; align-items: center; padding: 0 15px; flex-shrink: 0; z-index: 20; }
        .menu-btn { background: none; border: none; color: white; font-size: 24px; cursor: pointer; display: none; margin-right: 15px; }
        .brand { font-weight: bold; color: var(--accent); flex: 1; }
        .btn-logout { text-decoration: none; color: #888; font-size: 14px; border: 1px solid #444; padding: 5px 10px; border-radius: 4px; }

        .container { display: flex; flex: 1; height: calc(100vh - 50px); position: relative; }

        .sidebar { width: 260px; background: var(--sidebar-bg); border-right: 1px solid var(--border); display: flex; flex-direction: column; overflow-y: auto; flex-shrink: 0; transition: transform 0.3s ease; }
        
        .actions-bar { display: flex; gap: 10px; padding: 10px; }
        .btn-create { flex: 1; text-decoration: none; padding: 8px; text-align: center; border-radius: 4px; font-weight: bold; font-size: 14px; display: flex; align-items: center; justify-content: center; gap: 5px; color: white; }
        .btn-create.note { background: #238636; }
        .btn-create.task { background: #8957e5; }
        
        .note-list { list-style: none; padding: 0; margin: 0; }
        .note-item { display: block; padding: 15px; border-bottom: 1px solid #2a2a2a; color: #bbb; text-decoration: none; display: flex; align-items: center; gap: 10px; }
        .note-item:hover { background: #2a2a2a; }
        .note-item.active { border-left: 4px solid var(--accent); background: #252526; color: white; }
        .note-icon { font-size: 1.2em; }
        .note-info { flex: 1; overflow: hidden; }
        .note-date { font-size: 11px; color: #666; display: block; margin-top: 2px; }

        .editor { flex: 1; display: flex; flex-direction: column; min-width: 0; background: var(--bg); }
        .editor-form { display: flex; flex-direction: column; height: 100%; }
        
        .toolbar { padding: 10px; display: flex; gap: 10px; border-bottom: 1px solid var(--border); background: var(--bg); align-items: center; }
        input[name="titulo"] { flex: 1; background: transparent; border: none; border-bottom: 1px solid #444; color: white; padding: 8px; font-size: 16px; border-radius: 0; }
        input[name="titulo"]:focus { border-bottom-color: var(--accent); outline: none; }
        
        .btn-save { background: var(--accent); color: white; border: none; padding: 8px 15px; border-radius: 4px; font-weight: bold; cursor: pointer; }
        .btn-del { background: transparent; color: #ff5252; border: 1px solid #ff5252; padding: 8px; border-radius: 4px; text-decoration: none; }

        textarea { flex: 1; background: var(--bg); color: #d4d4d4; border: none; padding: 15px; resize: none; font-family: 'Consolas', monospace; font-size: 16px; outline: none; line-height: 1.5; }

        .checklist-area { flex: 1; overflow-y: auto; padding: 20px; }
        .add-item-row { display: flex; gap: 10px; margin-bottom: 20px; }
        .add-item-row input { flex: 1; background: #2d2d2d; border: 1px solid #444; color: white; padding: 10px; border-radius: 4px; font-size: 16px; }
        .btn-add-item { background: #2ea043; color: white; border: none; padding: 0 20px; border-radius: 4px; cursor: pointer; font-weight: bold; }
        
        .task-ul { list-style: none; padding: 0; margin: 0; }
        .task-li { display: flex; align-items: center; background: #1e1e1e; margin-bottom: 8px; padding: 10px; border-radius: 6px; gap: 10px; border: 1px solid #333; }
        .task-checkbox { width: 22px; height: 22px; cursor: pointer; accent-color: var(--success); }
        .task-text { flex: 1; font-size: 16px; word-break: break-word; }
        .task-text.done { text-decoration: line-through; color: #666; }
        .btn-rm-task { background: transparent; border: none; color: #666; cursor: pointer; font-size: 18px; padding: 5px 10px; }
        .btn-rm-task:hover { color: #ff5252; }

        @media (max-width: 768px) {
            .menu-btn { display: block; }
            .sidebar { position: absolute; top: 0; left: 0; height: 100%; z-index: 100; transform: translateX(-100%); width: 85%; box-shadow: 2px 0 10px rgba(0,0,0,0.5); }
            .sidebar.open { transform: translateX(0); }
            .overlay { display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 90; }
            .overlay.active { display: block; }
        }
    </style>
</head>
<body>

    <header>
        <button class="menu-btn" onclick="toggleMenu()">☰</button>
        <div class="brand">Code Vault</div>
        <a href="{{ url_for('logout') }}" class="btn-logout">Sair</a>
    </header>

    <div class="container">
        <div class="overlay" id="overlay" onclick="toggleMenu()"></div>

        <div class="sidebar" id="sidebar">
            <div class="actions-bar">
                <a href="{{ url_for('criar', tipo='texto') }}" class="btn-create note">📄 Nota</a>
                <a href="{{ url_for('criar', tipo='lista') }}" class="btn-create task">☑️ Lista</a>
            </div>
            <ul class="note-list">
                {% if notas|length == 0 %}
                    <div style="padding:20px; text-align:center; color:#555; font-size:0.9em;">Sem anotações.</div>
                {% endif %}
                {% for nota in notas %}
                    <a href="{{ url_for('index', id=nota.id) }}" onclick="toggleMenu()"
                       class="note-item {% if nota_ativa and nota_ativa.id == nota.id %}active{% endif %}">
                        <div class="note-icon">
                            {% if nota.tipo == 'lista' %}☑️{% else %}📄{% endif %}
                        </div>
                        <div class="note-info">
                            <strong>{{ nota.titulo }}</strong>
                            <span class="note-date">{{ nota.data_atualizacao.strftime('%d/%m %H:%M') }}</span>
                        </div>
                    </a>
                {% endfor %}
            </ul>
        </div>

        <div class="editor">
            <form action="{{ url_for('salvar') }}" method="POST" class="editor-form" id="mainForm">
                <input type="hidden" name="id" value="{{ nota_ativa.id if nota_ativa else '' }}">
                <input type="hidden" name="tipo" value="{{ nota_ativa.tipo if nota_ativa else 'texto' }}">
                <input type="hidden" name="conteudo_json" id="conteudo_json">

                <div class="toolbar">
                    <input type="text" name="titulo" placeholder="Título..." value="{{ nota_ativa.titulo if nota_ativa else '' }}" required autocomplete="off">
                    <button type="button" class="btn-save" onclick="submitForm()">Salvar</button>
                    
                    {% if nota_ativa and nota_ativa.id %}
                        <a href="{{ url_for('deletar', id=nota_ativa.id) }}" class="btn-del" onclick="return confirm('Apagar?')">🗑️</a>
                    {% endif %}
                </div>

                {% if nota_ativa and nota_ativa.tipo == 'lista' %}
                    <div class="checklist-area">
                        <div class="add-item-row">
                            <input type="text" id="newItemInput" placeholder="Nova tarefa..." onkeypress="handleEnter(event)" autocomplete="off">
                            <button type="button" class="btn-add-item" onclick="addTask()">Add</button>
                        </div>
                        <ul class="task-ul" id="taskList"></ul>
                    </div>
                {% else %}
                    <textarea name="conteudo_texto" placeholder="Escreva sua anotação..." spellcheck="false">{{ nota_ativa.conteudo if nota_ativa and nota_ativa.tipo != 'lista' else '' }}</textarea>
                {% endif %}
            </form>
        </div>
    </div>

    <script>
        function toggleMenu() {
            document.getElementById('sidebar').classList.toggle('open');
            document.getElementById('overlay').classList.toggle('active');
        }

        const isLista = {{ 'true' if nota_ativa and nota_ativa.tipo == 'lista' else 'false' }};
        let tasks = [];

        if (isLista) {
            try {
                const rawContent = `{{ nota_ativa.conteudo | safe if nota_ativa and nota_ativa.tipo == 'lista' else '[]' }}`;
                tasks = JSON.parse(rawContent);
                if (!Array.isArray(tasks)) tasks = [];
            } catch (e) { tasks = []; }
            renderTasks();
        }

        function renderTasks() {
            const list = document.getElementById('taskList');
            list.innerHTML = '';
            tasks.forEach((task, index) => {
                const li = document.createElement('li');
                li.className = 'task-li';
                li.innerHTML = `
                    <input type="checkbox" class="task-checkbox" ${task.done ? 'checked' : ''} onchange="toggleTask(${index})">
                    <span class="task-text ${task.done ? 'done' : ''}">${task.text}</span>
                    <button type="button" class="btn-rm-task" onclick="removeTask(${index})">✕</button>
                `;
                list.appendChild(li);
            });
        }

        function addTask() {
            const input = document.getElementById('newItemInput');
            const text = input.value.trim();
            if (text) {
                tasks.push({ text: text, done: false });
                input.value = '';
                renderTasks();
            }
            input.focus();
        }

        function toggleTask(index) {
            tasks[index].done = !tasks[index].done;
            renderTasks();
        }

        function removeTask(index) {
            tasks.splice(index, 1);
            renderTasks();
        }

        function handleEnter(e) {
            if (e.key === 'Enter') { e.preventDefault(); addTask(); }
        }

        function submitForm() {
            if (isLista) {
                document.getElementById('conteudo_json').value = JSON.stringify(tasks);
            }
            document.getElementById('mainForm').submit();
        }
    </script>
</body>
</html>
"""

# ================= BACKEND =================

class Nota(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    titulo = db.Column(db.String(150), nullable=False)
    conteudo = db.Column(db.Text, nullable=True)
    tipo = db.Column(db.String(20), default='texto')
    data_atualizacao = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)

corrigir_banco_de_dados()

with app.app_context():
    db.create_all()

@app.route('/', methods=['GET', 'POST'])
def index():
    if not session.get('logado'): return redirect(url_for('login'))
    
    nota_id = request.args.get('id')
    nota_ativa = None
    
    if nota_id:
        nota_ativa = Nota.query.get(nota_id)
    elif request.args.get('tipo'):
        # Cria um objeto temporário sem ID
        nota_ativa = Nota(titulo="", conteudo="", tipo=request.args.get('tipo'))
    
    notas = Nota.query.order_by(Nota.data_atualizacao.desc()).all()
    return render_template_string(HTML_INDEX, notas=notas, nota_ativa=nota_ativa)

@app.route('/criar/<tipo>')
def criar(tipo):
    return redirect(url_for('index', tipo=tipo))

@app.route('/login', methods=['GET', 'POST'])
def login():
    erro = None
    if request.method == 'POST':
        if request.form.get('senha') == SENHA_MESTRA:
            session['logado'] = True
            return redirect(url_for('index'))
        erro = "Senha incorreta"
    return render_template_string(HTML_LOGIN, erro=erro)

@app.route('/salvar', methods=['POST'])
def salvar():
    if not session.get('logado'): return redirect(url_for('login'))
    
    id_n = request.form.get('id')
    titulo = request.form.get('titulo')
    tipo = request.form.get('tipo')
    
    conteudo = request.form.get('conteudo_json') if tipo == 'lista' else request.form.get('conteudo_texto')

    if id_n and id_n != 'None' and id_n != '':
        nota = Nota.query.get(id_n)
        if nota:
            nota.titulo = titulo
            nota.conteudo = conteudo
    else:
        nova_nota = Nota(titulo=titulo, conteudo=conteudo, tipo=tipo)
        db.session.add(nova_nota)
        db.session.flush()
        id_n = nova_nota.id
    
    db.session.commit()
    return redirect(url_for('index', id=id_n))

@app.route('/deletar/<int:id>')
def deletar(id):
    if not session.get('logado'): return redirect(url_for('login'))
    nota = Nota.query.get(id)
    if nota:
        db.session.delete(nota)
        db.session.commit()
    return redirect(url_for('index'))

@app.route('/logout')
def logout():
    session.pop('logado', None)
    return redirect(url_for('login'))

if __name__ == '__main__':
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
    except:
        ip = "127.0.0.1"

    print("="*40)
    print(f"SISTEMA ONLINE (Versão Corrigida)")
    print(f"Local:   http://127.0.0.1:5000")
    print(f"Rede:    http://{ip}:5000")
    print("="*40)
    
    app.run(host='0.0.0.0', port=5000, debug=True)

