import re

with open('c:/projekty/plugin.video.mmirousek_v2/resources/lib/utils/cloud_sync.py', 'r', encoding='utf-8') as f:
    code = f.read()

# Změna 1
code = re.sub(
    r'(# Co synchronizovat\s+)self\.sync_json = addon\.getSettingBool\("cloud_sync_json"\)\s+self\.sync_sql = addon\.getSettingBool\("cloud_sync_sql"\)',
    r'\1self.sync_user_data = addon.getSettingBool("cloud_sync_user_data")',
    code
)

# Změna 2 - Smazat cesty a flag
code = re.sub(
    r'(\s*# Lokální cesty\s*self\.local_series_dir = .*?cloud_sync\.hash_migrated"\s*\)\n)',
    '', code, flags=re.DOTALL
)

# Změna 3 - Metody cest
code = re.sub(
    r'def _remote_json.*?def _remote_offline_settings',
    'def _remote_user_data(self):\n        return f"{self.root}/{self.username}/user_history_master.json"\n\n    def _remote_offline_settings',
    code, flags=re.DOTALL
)

# Změna 4 - Odstranit všechno staré JSON, Hash a SQL kód + nahradit Merge kódem
new_merge_code = '''    # ---------------------------------------------------------------------
    # Merge User Data
    # ---------------------------------------------------------------------
    def _sync_user_history(self):
        if not self.sync_user_data:
            return
            
        remote_path = self._remote_user_data()
        
        # 1. Lokální data (Export z DB)
        log.info("Exporting local user data...")
        local_data = db.export_user_data()
        
        # 2. Vzdálená data (Stáhnout z cloudu)
        remote_data = {"local_history": [], "search_history": []}
        remote_ts = self._remote_ts(remote_path)
        if remote_ts is not None:
            log.info("Downloading remote user data...")
            import io
            bio = io.BytesIO()
            try:
                self.ftp.retrbinary("RETR " + remote_path, bio.write)
                bio.seek(0)
                raw = bio.read().decode("utf-8", "ignore") or "{}"
                if raw.strip():
                    remote_data = json.loads(raw)
            except Exception as e:
                log.error(f"Failed to read remote user data: {e}")
                
        # 3. MERGE
        merged_data = self._merge_user_data(local_data, remote_data)
        
        # 4. Uložit zpět do DB
        db.import_merged_user_data(merged_data)
        
        # 5. Odeslat na cloud
        import io
        json_dump = json.dumps(merged_data, ensure_ascii=False)
        bio = io.BytesIO(json_dump.encode("utf-8"))
        tmp_remote = remote_path + ".part"
        try:
            self.ftp.storbinary("STOR " + tmp_remote, bio)
            # rename
            try:
                self.ftp.rename(tmp_remote, remote_path)
            except Exception:
                self.ftp.sendcmd("RNFR " + tmp_remote)
                self.ftp.sendcmd("RNTO " + remote_path)
            log.info("Uploaded merged user data to cloud.")
        except Exception as e:
            log.error(f"Failed to upload merged user data: {e}")
            try:
                self.ftp.delete(tmp_remote)
            except Exception:
                pass

    def _merge_user_data(self, local: dict, remote: dict) -> dict:
        merged = {"local_history": [], "search_history": []}
        
        # Merge search history
        search_dict = {}
        for x in remote.get("search_history", []):
            search_dict[x["query"]] = x.get("timestamp", 0)
        for x in local.get("search_history", []):
            q = x["query"]
            t = x.get("timestamp", 0)
            if q not in search_dict or t > search_dict[q]:
                search_dict[q] = t
        
        for q, t in search_dict.items():
            merged["search_history"].append({"query": q, "timestamp": t})
            
        # Merge local history (klíč je tmdb_id a media_type)
        history_dict = {}
        
        def _get_key(item):
            return f"{item.get('media_type')}_{item.get('tmdb_id')}"
            
        def _get_ts(item):
            val = item.get("watched_at", "1970-01-01 00:00:00")
            if not val: val = "1970-01-01 00:00:00"
            return val
            
        for x in remote.get("local_history", []):
            history_dict[_get_key(x)] = x
            
        for x in local.get("local_history", []):
            k = _get_key(x)
            if k not in history_dict:
                history_dict[k] = x
            else:
                ts_local = _get_ts(x)
                ts_remote = _get_ts(history_dict[k])
                if ts_local > ts_remote:
                    history_dict[k] = x
                    
        merged["local_history"] = list(history_dict.values())
        return merged

    # ---------------------------------------------------------------------
    # FULL SYNC
    # ---------------------------------------------------------------------
    def sync_all(self):
        if not self.enabled:
            log.info("Disabled → skip sync")
            return

        self._ensure_ftp()
        if not self.ftp:
            return

        try:
            self._ensure_remote_dirs()
            self._sync_user_history()
            log.info("Sync ALL complete")
        finally:
            self.close()

    # ---------------------------------------------------------------------
    # Hooky pro service'''

code = re.sub(
    r'    # ---------------------------------------------------------------------\s*# Hash čtení \(local / remote\).*?# ---------------------------------------------------------------------\s*# Hooky pro service',
    new_merge_code,
    code, flags=re.DOTALL
)

# Změna 5 - Odstranit delete_remote_json block
code = re.sub(
    r'    # ---------------------------------------------------------------------\s*# Smazání JSON souboru na FTP \(volat po remove_series\)\s*# ---------------------------------------------------------------------\s*def delete_remote_json\(self.*?finally:\s*self\.close\(\)\n',
    '', code, flags=re.DOTALL
)

with open('c:/projekty/plugin.video.mmirousek_v2/resources/lib/utils/cloud_sync.py', 'w', encoding='utf-8') as f:
    f.write(code)
print("cloud_sync.py updated successfully.")
