from flask import Flask, redirect, request, abort
import sqlite3

app = Flask(__name__)
DB = "links.db"

def get_db():
    db = sqlite3.connect(DB)
    db.row_factory = sqlite3.Row
    return db

def init_db():
    with get_db() as db:
        db.execute("""
            CREATE TABLE IF NOT EXISTS links (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                slug TEXT UNIQUE NOT NULL,
                url TEXT NOT NULL,
                label TEXT
            )
        """)

init_db()

HTML = """<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Links</title>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;700;800&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  :root { --bg: #0a0a0a; --surface: #111; --border: #222; --accent: #c8f25a; --text: #f0f0f0; --muted: #555; }
  body { background: var(--bg); color: var(--text); font-family: 'Syne', sans-serif; min-height: 100vh; padding: 2rem 1rem; }
  .container { max-width: 600px; margin: 0 auto; }
  h1 { font-size: clamp(2rem, 8vw, 3.5rem); font-weight: 800; letter-spacing: -0.03em; margin-bottom: 0.2rem; }
  h1 span { color: var(--accent); }
  .subtitle { color: var(--muted); font-family: 'DM Mono', monospace; font-size: 0.8rem; margin-bottom: 2.5rem; }
  .form { display: flex; gap: 0.5rem; margin-bottom: 2rem; flex-wrap: wrap; }
  input {
    background: var(--surface); border: 1px solid var(--border); color: var(--text);
    font-family: 'DM Mono', monospace; font-size: 0.85rem; padding: 0.65rem 1rem;
    border-radius: 6px; outline: none; flex: 1; min-width: 140px; transition: border-color 0.2s;
  }
  input:focus { border-color: var(--accent); }
  input::placeholder { color: var(--muted); }
  .btn {
    background: var(--accent); color: #000; border: none; font-family: 'Syne', sans-serif;
    font-weight: 700; font-size: 0.85rem; padding: 0.65rem 1.4rem; border-radius: 6px; cursor: pointer;
  }
  .btn:hover { opacity: 0.85; }
  .links { display: flex; flex-direction: column; gap: 0.6rem; }
  .link-card {
    display: flex; align-items: center;
    background: var(--surface); border: 1px solid var(--border); border-radius: 10px;
    padding: 1rem 1.25rem; color: var(--text); gap: 1rem;
    animation: fadeIn 0.3s ease both; transition: border-color 0.2s;
  }
  .link-card:hover { border-color: var(--accent); }
  @keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; } }
  .link-body { flex: 1; cursor: pointer; }
  .link-body:hover .link-label { color: var(--accent); }
  .link-label { font-weight: 700; font-size: 1rem; transition: color 0.2s; }
  .link-slug { font-family: 'DM Mono', monospace; font-size: 0.72rem; color: var(--accent); margin-top: 0.1rem; }
  .link-arrow { color: var(--muted); font-size: 1.2rem; flex-shrink: 0; cursor: pointer; }
  .del-btn {
    background: none; border: 1px solid #333; color: #555;
    font-size: 0.75rem; padding: 0.3rem 0.6rem; border-radius: 4px;
    cursor: pointer; flex-shrink: 0; transition: border-color 0.2s, color 0.2s;
  }
  .del-btn:hover { border-color: #ff4d6d; color: #ff4d6d; }
  .empty { color: var(--muted); font-family: 'DM Mono', monospace; font-size: 0.85rem; text-align: center; padding: 3rem 0; }
</style>
</head>
<body>
<div class="container">
  <h1>meus <span>links</span></h1>
  <p class="subtitle">// clique para acessar</p>

  <div class="form">
    <input type="text" id="slug" placeholder="slug (ex: yt)">
    <input type="text" id="label" placeholder="nome (ex: YouTube)">
    <input type="url" id="url" placeholder="https://...">
    <button class="btn" onclick="addLink()">+ add</button>
  </div>

  <div class="links" id="list"></div>
</div>

<script>
  async function loadLinks() {
    const res = await fetch('/api/links');
    const links = await res.json();
    const el = document.getElementById('list');
    if (!links.length) { el.innerHTML = '<p class="empty">nenhum link ainda.</p>'; return; }
    el.innerHTML = links.map((l, i) => `
      <div class="link-card" style="animation-delay:${i*0.05}s">
        <div class="link-body" onclick="location.href='/${l.slug}'">
          <div class="link-label">${l.label || l.slug}</div>
          <div class="link-slug">/${l.slug}</div>
        </div>
        <span class="link-arrow" onclick="location.href='/${l.slug}'">→</span>
        <button class="del-btn" onclick="deleteLink('${l.slug}')">✕</button>
      </div>
    `).join('');
  }

  async function addLink() {
    const slug = document.getElementById('slug').value.trim();
    const url = document.getElementById('url').value.trim();
    const label = document.getElementById('label').value.trim();
    if (!slug || !url) return;
    await fetch('/api/links', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ slug, url, label })
    });
    document.getElementById('slug').value = '';
    document.getElementById('url').value = '';
    document.getElementById('label').value = '';
    loadLinks();
  }

  async function deleteLink(slug) {
    await fetch('/api/links/' + slug, { method: 'DELETE' });
    loadLinks();
  }

  loadLinks();
</script>
</body>
</html>"""

@app.route("/")
def index():
    return HTML

@app.route("/api/links")
def list_links():
    with get_db() as db:
        rows = db.execute("SELECT slug, url, label FROM links ORDER BY id DESC").fetchall()
    return [dict(r) for r in rows]

@app.route("/api/links", methods=["POST"])
def add_link():
    data = request.json
    slug = data.get("slug", "").strip()
    url = data.get("url", "").strip()
    label = data.get("label", "").strip()
    if not slug or not url:
        return {"error": "slug e url obrigatórios"}, 400
    try:
        with get_db() as db:
            db.execute("INSERT INTO links (slug, url, label) VALUES (?, ?, ?)", (slug, url, label))
        return {"ok": True}
    except sqlite3.IntegrityError:
        return {"error": "slug já existe"}, 409

@app.route("/api/links/<slug>", methods=["DELETE"])
def delete_link(slug):
    with get_db() as db:
        db.execute("DELETE FROM links WHERE slug = ?", (slug,))
    return {"ok": True}

@app.route("/<slug>")
def do_redirect(slug):
    with get_db() as db:
        row = db.execute("SELECT url FROM links WHERE slug = ?", (slug,)).fetchone()
    if not row:
        abort(404)
    return redirect(row["url"])

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)
