#!/usr/bin/env python3
import tempfile
import unittest
import sqlite3
from pathlib import Path

import db


class TestDB(unittest.TestCase):
    def setUp(self) -> None:
        self.conn = sqlite3.connect(":memory:")
        self.conn.row_factory = sqlite3.Row
        db.ensure_schema(self.conn)

    def tearDown(self) -> None:
        self.conn.close()

    def test_normalize_url(self):
        self.assertEqual(
            db.normalize_url("http://Twitter.com/User/"),
            "https://x.com/User",
        )
        self.assertEqual(
            db.normalize_url("x.com/SomeUser/media/"),
            "https://x.com/SomeUser/media",
        )

    def test_add_link_dedupe(self):
        res1 = db.add_link(self.conn, "jawz", "https://x.com/Test/")
        res2 = db.add_link(self.conn, "jawz", "https://x.com/Test")
        self.assertEqual(res1["status"], "added")
        self.assertEqual(res2["status"], "exists")

    def test_remove_tombstone(self):
        db.add_link(self.conn, "jawz", "https://x.com/Test")
        ok = db.remove_link(self.conn, "jawz", "https://x.com/Test")
        self.assertTrue(ok)
        res = db.add_link(self.conn, "jawz", "https://x.com/Test")
        self.assertEqual(res["status"], "removed")
        res2 = db.add_link(self.conn, "jawz", "https://x.com/Test", assume_yes=True)
        self.assertEqual(res2["status"], "added")

    def test_disable_and_ban(self):
        db.add_link(self.conn, "jawz", "https://x.com/Test")
        ok = db.set_enabled(self.conn, "jawz", "https://x.com/Test", enabled=False)
        self.assertTrue(ok)
        active = db.get_active_links(self.conn, "jawz")
        self.assertEqual(active, [])
        ok = db.set_banned(self.conn, "jawz", "https://x.com/Test", banned=True, reason="bad")
        self.assertTrue(ok)
        active = db.get_active_links(self.conn, "jawz")
        self.assertEqual(active, [])

    def test_import_master_list(self):
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "watch.txt"
            path.write_text(
                "\n".join(
                    [
                        "https://x.com/User",
                        "# https://x.com/DisabledUser",
                        "https://x.com/User",
                    ]
                )
                + "\n",
                encoding="utf-8",
            )
            result = db.import_master_list(self.conn, "jawz", path)
            self.assertEqual(result["added"], 2)
            self.assertEqual(result["exists"], 1)
            rows = db.get_links_by_user(self.conn, "jawz")
            by_norm = {db.normalize_url(r["url_original"]): r for r in rows}
            self.assertTrue(by_norm["https://x.com/User"]["enabled"])
            self.assertFalse(by_norm["https://x.com/DisabledUser"]["enabled"])


if __name__ == "__main__":
    unittest.main()
