import sys
import os

# Add root directory to sys.path
sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(__file__))))

from automation.platform_handlers.base_handler import BasePlatformHandler
from automation.platform_handlers.instagram_handler import InstagramHandler
from automation.platform_handlers.facebook_handler import FacebookHandler
from automation.platform_handlers.pinterest_handler import PinterestHandler
from automation.platform_handlers.twitter_handler import TwitterHandler
from automation.platform_handlers.tiktok_handler import TikTokHandler
from automation.platform_handlers.generic_ai_handler import GenericAiHandler

class MockPage:
    def __init__(self, url="https://example.com"):
        self.url = url
        self._eval_store = {}

    def evaluate(self, script, arg=None):
        if "window.__last_copied_text" in script:
            return self._eval_store.get("__last_copied_text", "")
        return None

    def locator(self, sel):
        class MockLoc:
            def first(self):
                return self
            def is_visible(self, timeout=0):
                return False
            def all(self):
                return []
        return MockLoc()

def test_handler_interfaces():
    handlers = [
        ("Instagram", InstagramHandler()),
        ("Facebook", FacebookHandler()),
        ("Pinterest", PinterestHandler()),
        ("Twitter", TwitterHandler()),
        ("TikTok", TikTokHandler()),
        ("GenericAi", GenericAiHandler(domain="behance.net"))
    ]
    
    for name, h in handlers:
        print(f"Testing {name} Handler...")
        assert hasattr(h, "phase_upload"), f"{name} must have phase_upload"
        assert hasattr(h, "phase_metadata"), f"{name} must have phase_metadata"
        assert hasattr(h, "phase_publish"), f"{name} must have phase_publish"
        assert hasattr(h, "phase_extract_link"), f"{name} must have phase_extract_link"
        assert hasattr(h, "check_login_required"), f"{name} must have check_login_required"
        assert hasattr(h, "setup_clipboard_interceptor"), f"{name} must have setup_clipboard_interceptor"
        assert hasattr(h, "get_intercepted_clipboard"), f"{name} must have get_intercepted_clipboard"
        print(f"[OK] {name} implements all 4 phases and base methods correctly.")

def test_pipeline_abort_on_upload_failure():
    class DummyHandler(BasePlatformHandler):
        PLATFORM_NAME = "Dummy"
        def phase_upload(self, page, flyer_path, guide=None):
            return False  # Simulate upload failure
        def phase_metadata(self, page, title, caption, target_link=None, guide=None):
            raise AssertionError("Metadata should NOT be called when upload fails!")
        def phase_publish(self, page, guide=None):
            raise AssertionError("Publish should NOT be called when upload fails!")
        def phase_extract_link(self, page, title, guide=None):
            raise AssertionError("Extract Link should NOT be called when upload fails!")

    dummy = DummyHandler()
    res = dummy.post(MockPage(), "dummy.jpg", "Title", "Caption")
    assert res["success"] is False
    assert "FAILED: Sesi 1 (Upload Media)" in res["message"]
    print("[OK] Pipeline aborts properly if Sesi 1 (Upload) fails.")

def test_pipeline_abort_on_publish_failure():
    class DummyHandler2(BasePlatformHandler):
        PLATFORM_NAME = "Dummy2"
        def phase_upload(self, page, flyer_path, guide=None):
            return True
        def phase_metadata(self, page, title, caption, target_link=None, guide=None):
            return True
        def phase_publish(self, page, guide=None):
            return False  # Simulate publish failure
        def phase_extract_link(self, page, title, guide=None):
            raise AssertionError("Extract Link should NOT be called when publish fails!")

    dummy2 = DummyHandler2()
    res = dummy2.post(MockPage(), "dummy.jpg", "Title", "Caption")
    assert res["success"] is False
    assert "FAILED: Sesi 3 (Publikasi)" in res["message"]
    print("[OK] Pipeline aborts properly if Sesi 3 (Publikasi) fails.")

def test_pipeline_success():
    class DummyHandler3(BasePlatformHandler):
        PLATFORM_NAME = "Dummy3"
        def phase_upload(self, page, flyer_path, guide=None):
            return True
        def phase_metadata(self, page, title, caption, target_link=None, guide=None):
            return True
        def phase_publish(self, page, guide=None):
            return True
        def phase_extract_link(self, page, title, guide=None):
            return {"success": True, "post_url": "https://dummy.com/p/123", "message": "Success"}

    dummy3 = DummyHandler3()
    res = dummy3.post(MockPage(), "dummy.jpg", "Title", "Caption")
    assert res["success"] is True
    assert res["post_url"] == "https://dummy.com/p/123"
    print("[OK] Pipeline completes all 4 phases and returns valid post URL on success.")

def test_check_login_required():
    base = BasePlatformHandler()
    
    # Test login URLs
    assert base.check_login_required(MockPage(url="https://x.com/i/flow/login")) is True
    assert base.check_login_required(MockPage(url="https://www.tiktok.com/login")) is True
    assert base.check_login_required(MockPage(url="https://www.instagram.com/accounts/login/")) is True
    assert base.check_login_required(MockPage(url="https://example.com/feed")) is False
    print("[OK] check_login_required accurately detects unauthenticated URLs.")

def test_clipboard_interceptor():
    base = BasePlatformHandler()
    page = MockPage()
    base.setup_clipboard_interceptor(page)
    page._eval_store["__last_copied_text"] = "https://instagram.com/p/C_TEST123/"
    assert base.get_intercepted_clipboard(page) == "https://instagram.com/p/C_TEST123/"
    print("[OK] Clipboard interceptor accurately captures copied links.")

if __name__ == "__main__":
    test_handler_interfaces()
    test_check_login_required()
    test_clipboard_interceptor()
    test_pipeline_abort_on_upload_failure()
    test_pipeline_abort_on_publish_failure()
    test_pipeline_success()
    print("\nALL 4-PHASE UNIT TESTS PASSED SUCCESSFULLY!")
