import os
import time
import sqlite3
from datetime import datetime
import pyperclip

# ------------------------------------------------------------
# PATHS
# ------------------------------------------------------------
DB_PATH = r"c:\Temp\projectClipboard\DB\clipboard.db"
HTML_PATH = r"c:\Temp\projectClipboard\clipboard.html"

os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
os.makedirs(os.path.dirname(HTML_PATH), exist_ok=True)

# ------------------------------------------------------------
# DATABASE SETUP
# ------------------------------------------------------------
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()

cur.execute("""
CREATE TABLE IF NOT EXISTS clipboard (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    timestamp TEXT NOT NULL,
    content TEXT NOT NULL
)
""")

conn.commit()

# ------------------------------------------------------------
# HTML REPORT GENERATOR
# ------------------------------------------------------------
def generate_html():
    conn = sqlite3.connect(DB_PATH)
    cur = conn.cursor()
    cur.execute("SELECT id, timestamp, content FROM clipboard ORDER BY id DESC")
    rows = cur.fetchall()
    conn.close()

    html = f"""
<!DOCTYPE html>
<html>
<head>
<title>Clipboard Monitor</title>
<style>
    body {{
        font-family: Arial, sans-serif;
        background: #1e1e1e;
        color: #e0e0e0;
        padding: 20px;
    }}
    h1 {{
        color: #4fc3f7;
    }}
    table {{
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }}
    th {{
        background: #333;
        padding: 10px;
        border-bottom: 2px solid #555;
    }}
    td {{
        padding: 8px;
        border-bottom: 1px solid #444;
        vertical-align: top;
        white-space: pre-wrap;
    }}
    tr:hover {{
        background: #2a2a2a;
    }}
</style>
</head>
<body>

<h1>Clipboard Monitor</h1>
<p>Last updated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</p>

<table>
<tr>
    <th>ID</th>
    <th>Timestamp</th>
    <th>Clipboard Content</th>
</tr>
"""

    for row in rows:
        html += f"""
<tr>
    <td>{row[0]}</td>
    <td>{row[1]}</td>
    <td>{row[2]}</td>
</tr>
"""

    html += """
</table>
</body>
</html>
"""

    with open(HTML_PATH, "w", encoding="utf-8") as f:
        f.write(html)

    print(f"HTML updated: {HTML_PATH}")

# ------------------------------------------------------------
# CLIPBOARD MONITOR LOOP
# ------------------------------------------------------------
def monitor_clipboard():
    print("📋 Clipboard monitor started. Press CTRL+C to stop.")
    last_text = ""

    while True:
        try:
            text = pyperclip.paste()

            if text != last_text and text.strip() != "":
                timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                print(f"\n🔹 New clipboard content detected at {timestamp}")
                print("-----")
                print(text)
                print("-----")

                conn = sqlite3.connect(DB_PATH)
                cur = conn.cursor()
                cur.execute("INSERT INTO clipboard (timestamp, content) VALUES (?, ?)", (timestamp, text))
                conn.commit()
                conn.close()

                generate_html()

                last_text = text

            time.sleep(0.5)

        except KeyboardInterrupt:
            print("\n🛑 Clipboard monitor stopped.")
            break

# ------------------------------------------------------------
# RUN MONITOR
# ------------------------------------------------------------
monitor_clipboard()
