Kamel Barkaoui

199 papers A 2B 11C 35Misc 6Journal 67Unranked 74
YearRankTypeTitle / Venue / Authors
2026 J jnl
IACR Cryptol. ePrint Arch.
Ikhlas Mastour, Layth Sliman, Boussad Ait Salem, Balthazar Bauer, Raoudha Ben Djemaa, Kamel Barkaoui
2025 J jnl
SN Comput. Sci.
Ines Gharbi, Mohamed Belaoued, Abdelouahid Derhab, Kamel Barkaoui
2025 ed.
CARI
Djamil Aïssani, Kamel Barkaoui, Mathieu Roche
2025 J jnl
Comput. Networks
Mohamed Escheikh, Wiem Taktak, Kamel Barkaoui
2024 C conf
VECoS
Wiem Taktak, Mohamed Escheikh, Kamel Barkaoui
2024 J jnl
Comput. Networks
Wiem Taktak, Mohamed Escheikh, Kamel Barkaoui
2024 C conf
MEDES
Bachar Kachouh, Layth Sliman, Abed Ellatif Samhat, Kamel Barkaoui
2024 J jnl
Innov. Syst. Softw. Eng.
Kamel Barkaoui, Belgacem Ben Hedia
2024 J jnl
Soft Comput.
Walid Ben Mesmia, Kamel Barkaoui
2024 C conf
CoDIT
Zexi Huang, Lin Chen, Gaiyun Liu, Kamel Barkaoui
2023 C conf
VECoS
Wiem Taktak, Mohamed Escheikh, Kamel Barkaoui
2023 conf
ICNSC
Ammar Boucherit, Kamel Barkaoui, Mohammed Lamine Lamouri
2023 J jnl
Inf. Sci.
Umar Suleiman Abubakar, Gaiyun Liu, Kamel Barkaoui, ZhiWu Li
2023 conf
ICNSC
Chen Shen, Gaiyun Liu, Chunfu Zhong, Kamel Barkaoui
2023 conf
ACSW
Bachar Kachouh, Layth Sliman, Abed Ellatif Samhat, Kamel Barkaoui
2023 conf
ICCA
Ikhlas Mastour, Layth Sliman, Benoit Charroux, Raoudha Ben Djemaa, Kamel Barkaoui
2023 C conf
ICTSS
Mohamed Escheikh, Wiem Taktak, Kamel Barkaoui
2022 J jnl
IEEE Trans. Syst. Man Cybern. Syst.
Ziliang Zhang, Gaiyun Liu, Kamel Barkaoui, ZhiWu Li
2022 J jnl
IEEE Access
Rateb Jabbar, Eya Dhib, Ahmed Ben Said, Moez Krichen, Noora Fetais, Esmat Zaidan, Kamel Barkaoui
2022 J jnl
Autom.
Hanifa Boucheneb, Kamel Barkaoui, Qian Xing, Kuangze Wang, Gaiyun Liu, ZhiWu Li
2022 C ed.
VECoS
Ayoub Nouri, Weimin Wu, Kamel Barkaoui, ZhiWu Li
2021 conf
PNSE@Petri Nets
Ammar Boucherit, Kamel Barkaoui, Osman Hasan
2021 J jnl
IEEE CAA J. Autom. Sinica
Shouguang Wang, Wenli Duo, Xin Guo, Xiaoning Jiang, Dan You, Kamel Barkaoui, MengChu Zhou
2021 J jnl
J. Softw. Evol. Process.
Walid Ben Mesmia, Mohamed Escheikh, Kamel Barkaoui
2021 J jnl
Expert Syst. Appl.
Hossain Kordestani, Roghayeh Mojarad, Abdelghani Chibani, Kamel Barkaoui, Yacine Amirat, Wagdy Zahran
2020 B conf
ENASE
Rateb Jabbar, Moez Krichen, Mohamed Kharbeche, Noora Fetais, Kamel Barkaoui
2020 B conf
IWCMC
Rateb Jabbar, Moez Krichen, Mohammed Shinoy, Mohamed Kharbeche, Noora Fetais, Kamel Barkaoui
2020 conf
ICEIS (1)
Rateb Jabbar, Moez Krichen, Noora Fetais, Kamel Barkaoui
2020 conf
MSPN
Ines Gharbi, Kamel Barkaoui, Samir Ben Ahmed
2020 J jnl
Sensors
Rateb Jabbar, Mohamed Kharbeche, Khalifa Al-Khalifa, Moez Krichen, Kamel Barkaoui
2020 conf
ICIoT
Rateb Jabbar, Noora Fetais, Moez Krichen, Kamel Barkaoui
2020 conf
ICIoT
Rateb Jabbar, Mohammed Shinoy, Mohamed Kharbeche, Khalifa Al-Khalifa, Moez Krichen, Kamel Barkaoui
2020 J jnl
CoRR
Rateb Jabbar, Mohammed Shinoy, Mohamed Kharbeche, Khalifa Al-Khalifa, Moez Krichen, Kamel Barkaoui
2020 J jnl
Innov. Syst. Softw. Eng.
Kamel Barkaoui, Hanifa Boucheneb, ZhiWu Li
2020 conf
SeGAH
Hossain Kordestani, Kamel Barkaoui, Wagdy Zahran
2020 conf
EMCIS
Hossain Kordestani, Kamel Barkaoui, Wagdy Zahran
2020 C conf
VECoS
Kuangze Wang, Hanifa Boucheneb, Kamel Barkaoui, ZhiWu Li
2020 J jnl
CoRR
Rateb Jabbar, Mohammed Shinoy, Mohamed Kharbeche, Khalifa Al-Khalifa, Moez Krichen, Kamel Barkaoui
2019 J jnl
IEEE Access
Xiaoyan Li, Gaiyun Liu, ZhiWu Li, Naiqi Wu, Kamel Barkaoui
2019 C conf
AICCSA
Hossain Kordestani, Roghayeh Mojarad, Abdelghani Chibani, Aomar Osmani, Yacine Amirat, Kamel Barkaoui, Wagdy Zahran
2019 B conf
KES
Meriem Zouita, Sadok Bouamama, Kamel Barkaoui
2019 J jnl
IEEE Access
Hao Dou, Kamel Barkaoui, Hanifa Boucheneb, Xiaoning Jiang, Shouguang Wang
2019 C conf
CoDIT
Rym Meriah, Kamel Barkaoui, Gaiyun Liu, Olfa Belkahla Driss
2019 J jnl
Int. J. Crit. Comput. Based Syst.
Mohamed Escheikh, Zayneb Tayachi, Kamel Barkaoui
2019 conf
SDS
Mohamed Escheikh, Kamel Barkaoui
2019 conf
IINTEC
Rateb Jabbar, Mohammed Shinoy, Mohamed Kharbeche, Khalifa Al-Khalifa, Moez Krichen, Kamel Barkaoui
2018 J jnl
Int. J. Comput. Appl. Technol.
Manel Amel Djenouhat, Faiza Belala, Kamel Barkaoui
2018 J jnl
Real Time Syst.
Hanifa Boucheneb, Kamel Barkaoui
2018 C conf
VECoS
Kamel Barkaoui, Hanifa Boucheneb, ZhiWu Li
2018 J jnl
Innov. Syst. Softw. Eng.
Kamel Barkaoui, Hanifa Boucheneb
2018 J jnl
IEEE CAA J. Autom. Sinica
Naiqi Wu, ZhiWu Li, Kamel Barkaoui, Xiaoou Li, Tadahiko Murata, MengChu Zhou
2018 B conf
SMC
Dan You, Shouguang Wang, Hao Dou, Wenli Duo, Kamel Barkaoui, Carla Seatzu
2018 conf
FORMATS
Kamel Barkaoui, Hanifa Boucheneb
2018 J jnl
Int. J. Crit. Comput. Based Syst.
Assia Outamazirt, Mohamed Escheikh, Djamil Aïssani, Kamel Barkaoui, Ouiza Lekadir
2017 J jnl
IEEE Trans. Syst. Man Cybern. Syst.
Yufeng Chen, ZhiWu Li, Kamel Barkaoui, Naiqi Wu, MengChu Zhou
2017 J jnl
Inf. Sci.
Ahmed Kheldoun, Kamel Barkaoui, Malika Ioualalen
2017 C conf
VECoS
Hana Jouini, Mohamed Escheikh, Kamel Barkaoui, Tahar Ezzedine
2017 J jnl
Int. J. Crit. Comput. Based Syst.
Mohamed Escheikh, Kamel Barkaoui
2017 J jnl
IEEE Access
Chengzong Li, Yufeng Chen, ZhiWu Li, Kamel Barkaoui
2017 C ed.
VECoS
Kamel Barkaoui, Hanifa Boucheneb, Ali Mili, Sofiène Tahar
2017 J jnl
J. Syst. Softw.
Mohamed Escheikh, Kamel Barkaoui, Hana Jouini
2016 C conf
WETICE
Hanane Ariouat, Awatef Hicheur Cairns, Kamel Barkaoui, Jacky Akoka, Nasser Khelifa
2016 J jnl
Int. J. Crit. Comput. Based Syst.
Taha Abdelmoutaleb Cherfia, Faïza Belala, Kamel Barkaoui
2016 J jnl
Inf. Sci.
Gaiyun Liu, Kamel Barkaoui
2016 J jnl
Int. J. Inf. Syst. Serv. Sect.
Aymen Louati, Kamel Barkaoui
2016 conf
ICNC-FSKD
Sonia Alouane-Ksouri, Minyar Sassi Hidri, Kamel Barkaoui
2016 J jnl
CoRR
Mohamed Escheikh, Hana Jouini, Kamel Barkaoui
2016 conf
WODES
Kamel Barkaoui, Awatef Hicheur, Ahmed Kheldoun, Ding Liu
2016 C conf
VECoS
Assia Outamazirt, Mohamed Escheikh, Djamil Aïssani, Kamel Barkaoui, Ouiza Lekadir
2016 conf
IntelliSys (2)
Walid Ben Mesmia, Borhen Marzougui, Kamel Barkaoui
2016 J jnl
Multiagent Grid Syst.
Ahmed Taki Eddine Dib, Kamel Barkaoui, Zaïdi Sahnoun
2016 conf
ISSRE Workshops
Mohamed Escheikh, Zayneb Tayachi, Kamel Barkaoui
2015 conf
CIIA
Ahmed Kheldoun, Kamel Barkaoui, Jiafeng Zhang, Malika Ioualalen
2015 J jnl
ACM Trans. Embed. Comput. Syst.
Kamel Barkaoui, Luca Bernardinello, Andrey Mokhov
2015 J jnl
Int. J. Syst. Sci.
Gaiyun Liu, Kamel Barkaoui
2015 C conf
VECoS
Zohra Sbaï, Kamel Barkaoui
2015 J jnl
Autom.
Yufeng Chen, ZhiWu Li, Kamel Barkaoui, Alessandro Giua
2015 A conf
BPM
Ahmed Kheldoun, Kamel Barkaoui, Malika Ioualalen
2015 C conf
VECoS
Amira Methni, Matthieu Lemerre, Belgacem Ben Hedia, Serge Haddad, Kamel Barkaoui
2015 conf
ACSD
Hanifa Boucheneb, Kamel Barkaoui
2015 J jnl
ACM Trans. Embed. Comput. Syst.
Hanifa Boucheneb, Kamel Barkaoui
2015 ch.
Formalisms for Reuse and Systems Integration
Aymen Louati, Kamel Barkaoui, Chadlia Jerad
2014 C conf
EUC
Taha Abdelmoutaleb Cherfia, Kamel Barkaoui, Faiza Belala
2014 conf
ADECS @ Petri Nets
Ahmed Kheldoun, Jiafeng Zhang, Kamel Barkaoui, Malika Ioualalen
2014 B conf
MASCOTS
Mohamed Escheikh, Hana Jouini, Kamel Barkaoui
2014 conf
FSKD
Sonia Alouane-Ksouri, Minyar Sassi Hidri, Kamel Barkaoui
2014 conf
PNSE @ Petri Nets
Zohra Sbaï, Kamel Barkaoui, Hanifa Boucheneb
2014 conf
FORMATS
Hanifa Boucheneb, Kamel Barkaoui, Karim Weslati
2014 J jnl
CoRR
Aymen Louati, Chadlia Jerad, Kamel Barkaoui
2014 J jnl
Int. J. Serv. Sci. Manag. Eng. Technol.
Minyar Sassi Hidri, Sonia Alouane-Ksouri, Kamel Barkaoui
2014 conf
ICNSC
Ding Liu, Yifan Hou, Kamel Barkaoui, MengChu Zhou
2014 conf
WODES
Yufeng Chen, ZhiWu Li, Kamel Barkaoui
2014 J jnl
Inf. Sci.
Yufeng Chen, ZhiWu Li, Kamel Barkaoui
2014 J jnl
IEEE Trans. Syst. Man Cybern. Syst.
Yufeng Chen, ZhiWu Li, Kamel Barkaoui, Murat Uzam
2014 conf
EOMAS@CAiSE
Zohra Sbaï, Kamel Barkaoui
2014 J jnl
Int. J. Crit. Comput. Based Syst.
Hanifa Boucheneb, Kamel Barkaoui
2014 J jnl
Inf. Sci.
Hanifa Boucheneb, Kamel Barkaoui
2014 conf
FTSCS
Amira Methni, Matthieu Lemerre, Belgacem Ben Hedia, Serge Haddad, Kamel Barkaoui
2014 conf
DEXA Workshops
Sonia Alouane-Ksouri, Minyar Sassi Hidri, Kamel Barkaoui
2014 Misc conf
IRI
Aymen Louati, Kamel Barkaoui, Chadlia Jerad
2014 C conf
VECoS
Taha Abdelmoutaleb Cherfia, Faiza Belala, Kamel Barkaoui
2014 J jnl
Int. J. Crit. Comput. Based Syst.
Sabine Boufenara, Kamel Barkaoui, Faiza Belala, Hanifa Boucheneb
2013 conf
IRI (best papers)
Nesrine Harrath, Bruno Monsuez, Kamel Barkaoui
2013 conf
DEXA Workshops
Sonia Alouane-Ksouri, Minyar Sassi Hidri, Kamel Barkaoui
2013 conf
HPCS
Ridha Benosman, Kamel Barkaoui, Yves Albrieux
2013 conf
CSE
Maryam Eslamichalandar, Kamel Barkaoui, Hamid Reza Motahari-Nezhad
2013 B conf
ICECCS
Ridha Benosman, Kamel Barkaoui, Yves Albrieux
2013 conf
ICCA
Ding Liu, Yifan Hou, Hesuan Hu, Kamel Barkaoui, MengChu Zhou
2013 J jnl
CoRR
Sonia Alouane-Ksouri, Minyar Sassi Hidri, Kamel Barkaoui
2013 J jnl
Int. J. Recent Contributions Eng. Sci. IT
Sonia Alouane-Ksouri, Minyar Sassi Hidri, Kamel Barkaoui
2013 J jnl
ACM Trans. Embed. Comput. Syst.
Hanifa Boucheneb, Kamel Barkaoui
2013 J jnl
Inf. Sci.
Gaiyun Liu, ZhiWu Li, Kamel Barkaoui, Abdulrahman Al-Ahmari
2013 Misc conf
IRI
Nesrine Harrath, Bruno Monsuez, Kamel Barkaoui
2013 J jnl
CoRR
Zohra Sbaï, Kamel Barkaoui
2013 J jnl
Ingénierie des Systèmes d Inf.
Zohra Sbaï, Kamel Barkaoui
2012 ed.
Business Process Management Workshops (1)
Florian Daniel, Kamel Barkaoui, Schahram Dustdar
2012 ed.
Business Process Management Workshops (2)
Florian Daniel, Kamel Barkaoui, Schahram Dustdar
2012 conf
Business Process Management Workshops
Borhen Marzougui, Khaled Hassine, Kamel Barkaoui
2012 conf
FHIES
Awatef Hicheur, Amel Ben Dhieb, Kamel Barkaoui
2012 C conf
ISCC
Mohamed Escheikh, Kamel Barkaoui
2012 J jnl
Int. J. Found. Comput. Sci.
Hammadi Bennoui, Allaoua Chaoui, Kamel Barkaoui
2012 conf
WODES
Ding Liu, Kamel Barkaoui, MengChu Zhou
2012 C conf
SEKE
Hanifa Boucheneb, Kamel Barkaoui
2012 conf
SOCA
Ridha Benosman, Yves Albrieux, Kamel Barkaoui
2012 conf
ACSD
Hanifa Boucheneb, Kamel Barkaoui
2011 J jnl
Int. J. Crit. Comput. Based Syst.
Chafia Bouanaka, Faiza Belala, Kamel Barkaoui
2011 J jnl
Tech. Sci. Informatiques
Malika Benammar, Faiza Belala, Kamel Barkaoui
2011 conf
Business Process Management Workshops (2)
Amel Ben Dhieb, Kamel Barkaoui
2011 C conf
ETFA
Yufeng Chen, ZhiWu Li, Kamel Barkaoui
2011 conf
Q2SWinet
Mohamed Escheikh, Kamel Barkaoui
2011 J jnl
Discret. Event Dyn. Syst.
Hanifa Boucheneb, Kamel Barkaoui
2011 conf
NOTERE
Faiza Belala, Chafia Bouanaka, Kamel Barkaoui
2010 J jnl
J. Softw. Eng. Appl.
Abdallah Missaoui, Kamel Barkaoui
2010 J jnl
J. Softw. Eng. Appl.
Borhen Marzougui, Khaled Hassine, Kamel Barkaoui
2010 J jnl
J. Softw. Eng. Appl.
Aicha Choutri, Faiza Belala, Kamel Barkaoui
2010 conf
Q2SWinet
Robert Abo, Kamel Barkaoui, Hafedh Zayani
2010 J jnl
J. Softw. Eng. Appl.
Sabine Boufenara, Faiza Belala, Kamel Barkaoui
2010 conf
ACT4SOC
Abdallah Missaoui, Zohra Sbaï, Kamel Barkaoui
2010 J jnl
Multiagent Grid Syst.
Yacine Kissoum, Zaïdi Sahnoun, Kamel Barkaoui
2010 conf
INFINITY
Hanifa Boucheneb, Kamel Barkaoui
2010 J jnl
Concurr. Comput. Pract. Exp.
Mohamed Escheikh, Kamel Barkaoui
2010 J jnl
CoRR
Hafedh Zayani, Kamel Barkaoui, Rahma Ben Ayed
2010 conf
EMS
Borhen Marzougui, Khaled Hassine, Kamel Barkaoui
2010 conf
ICDCS Workshops
Robert Abo, Kamel Barkaoui, Karim Djouani
2009 B conf
RCIS
Yacine Kissoum, Zaïdi Sahnoun, Kamel Barkaoui
2009 conf
ICEIS (3)
Kamel Barkaoui, Chafia Bouanaka, José Martín Molina Espinosa
2009 conf
INFINITY
Hanifa Boucheneb, Kamel Barkaoui
2009 C conf
ISPDC
Hammadi Bennoui, Allaoua Chaoui, Kamel Barkaoui
2009 conf
CAL
Malika Benammar, Faiza Belala, Kamel Barkaoui, Nadira Benlahrache
2009 C conf
AICCSA
Nasreddine Aoumeur, Kamel Barkaoui, Gunter Saake
2009 C conf
ISCC
Mohamed Escheikh, Kamel Barkaoui
2009 C conf
IEEE International Workshop on Rapid System Prototyping
Nasreddine Aoumeur, Kamel Barkaoui, Gunter Saake
2009 conf
SOCA
Nasreddine Aoumeur, Kamel Barkaoui
2009 C conf
ICIW
Nasreddine Aoumeur, Kamel Barkaoui
2009 conf
ECBS
Nasreddine Aoumeur, Kamel Barkaoui, Gunter Saake
2008 C conf
APSCC
Karim Djouani, Jun Chen, Abdellah Akharraz, Kamel Barkaoui
2008 J jnl
Formal Aspects Comput.
Kamel Barkaoui, Manfred Broy, Ana Cavalcanti, Antonio Cerone
2008 conf
WS-FM
Kamel Barkaoui, Hanifa Boucheneb, Awatef Hicheur
2008 conf
NOTERE
Awatef Hicheur, Kamel Barkaoui
2008 conf
SITIS
Nasreddine Aoumeur, Kamel Barkaoui, Claus Rautenstrauch
2008 conf
BCS Int. Acad. Conf.
Chadlia Jerad, Kamel Barkaoui, Amel Grissa Touzi
2008 conf
FORMATS
Hanifa Boucheneb, Kamel Barkaoui
2008 conf
ITNG
Nasreddine Aoumeur, Kamel Barkaoui, Gunter Saake
2008 B conf
RCIS
Aicha Choutri, Faiza Belala, Kamel Barkaoui
2008 C conf
CRiSIS
Kamel Barkaoui, Rahma Ben Ayed, Hanifa Boucheneb, Awatef Hicheur
2007 conf
ICEIS (3)
Nasreddine Aoumeur, Gunter Saake, Kamel Barkaoui
2007 conf
PM2HW2N
Hafedh Zayani, Rahma Ben Ayed, Karim Djouani, Kamel Barkaoui
2007 B conf
ECSA
Chadlia Jerad, Kamel Barkaoui, Amel Grissa Touzi
2007 conf
CSMR
Nasreddine Aoumeur, Kamel Barkaoui, Gunter Saake
2007 Misc conf
CATA
Chadlia Jerad, Kamel Barkaoui, Amel Grissa Touzi
2007 conf
WEBIST (1)
Abdallah Missaoui, Kamel Barkaoui
2007 conf
Business Process Management Workshops
Kamel Barkaoui, Awatef Hicheur
2006 C conf
AICCSA
Nadia Zeghib, Kamel Barkaoui, Mohamed Bettaz
2006 Misc conf
SYNASC
Awatef Hicheur, Kamel Barkaoui, Noura Boudiaf
2006 C ed.
ICTAC
Kamel Barkaoui, Ana Cavalcanti, Antonio Cerone
2005 Misc conf
PDPTA
Hacene Sebih, Kamel Barkaoui
2005 A conf
ESA
Nadia Zeghib, Mohamed Bettaz, Kamel Barkaoui
2005 conf
ICATPN
Kamel Barkaoui, Jean-Michel Couvreur, Kais Klai
2005 C conf
IEEE International Workshop on Rapid System Prototyping
Chadlia Jerad, Kamel Barkaoui
2005 C conf
AICCSA
Laid Kahloul, Kamel Barkaoui, Zaïdi Sahnoun
2003 J jnl
J. Supercomput.
Kamel Barkaoui, Rabah Benamara
2003 B conf
SMC
Belhassen Zouari, Kamel Barkaoui
2002 J jnl
J. Syst. Softw.
Kamel Barkaoui, Mohamed Jmaiel, Ali Mili
2002 conf
HICSS
Kamel Barkaoui, Ph. Dechambre, R. Hachicha
2000 B conf
MASCOTS
Mohamed Escheikh, Kamel Barkaoui, Ammar Bouallegue
1999 Misc conf
PDPTA
Kamel Barkaoui, Rabah Benamara
1998 conf
HASE
Kamel Barkaoui, Jean-François Pradat-Peyre
1997 C conf
DEXA
Kamel Barkaoui, Yasmina Maïzi
1997 C conf
APSEC
Kamel Barkaoui, Claude Kaiser, Jean-François Pradat-Peyre
1997 conf
FTDCS
Kamel Barkaoui, Rabah Benamara
1996 conf
EUROMICRO
Mohamed Bettaz, Mourad Maouche, Kamel Barkaoui
1996 conf
Application and Theory of Petri Nets
Kamel Barkaoui, Jean-François Pradat-Peyre
1996 conf
DEXA Workshop
Kamel Barkaoui, Yasmina Maïzi
1995 conf
Application and Theory of Petri Nets
Kamel Barkaoui, Jean-Michel Couvreur, Claude Dutheillet
1993 conf
Application and Theory of Petri Nets
Kamel Barkaoui, Claude Dutheillet, Serge Haddad
1992 conf
Application and Theory of Petri Nets
Kamel Barkaoui, Michel Minoux
1992 C conf
DEXA
Kamel Barkaoui, Noureddine Boudriga, Amel Grissa Touzi
1990 J jnl
Discret. Appl. Math.
Michel Minoux, Kamel Barkaoui
1988 conf
FTCS
Kamel Barkaoui, Gerard Florin, Céline Fraize, Bernard Lemaire, Stéphane Natkin
redb/extractors/decompiler/DecompileAPK.py
← Index redb/extractors/decompiler/DecompileAPK.py python
"""APK Code Analysis Extractor.

Decompiles and disassembles APK DEX bytecode at the method level,
producing per-method content and reference records analogous to
the Binary Ninja code_binja_* tables.

Uses androguard + JADX + apktool to replicate Binary Ninja analysis
depth for Android applications.
"""

import gc
import hashlib
import inspect
import logging
import os
import threading
import time
from datetime import datetime, timezone
from typing import Any, Dict, Optional

from redb.extractors.decompiler.apk.analyzer import APKCodeAnalyzer
from redb.extractors.enum import Tag
from redb.extractors.extractor import Extractor


class DecompileAPK(Extractor):
    """APK code analysis extractor — produces multi-table ClickHouse export.

    Follows the same pattern as DecompileBinja for consistency.
    """

    def __init__(
        self,
        filepath,
        log,
        exporters=None,
        index_prefix=None,
        known_benign=False,
        known_malicious=False,
        filetype=None,
        decompile_modules=None,
    ):
        super().__init__(
            filepath,
            log,
            exporters,
            index_prefix,
            known_benign=known_benign,
            known_malicious=known_malicious,
        )
        self.log.debug(inspect.currentframe().f_code.co_name)
        self.analysis_results = None
        self.analyzer = None
        self.filetype = filetype or "apk"
        self.decompile_modules = decompile_modules or {"all"}

        try:
            self.APK_DECOMPILE_TIMEOUT = int(
                os.getenv("APK_DECOMPILE_TIMEOUT", "600")
            )
        except ValueError:
            self.log.warning(
                "Invalid APK_DECOMPILE_TIMEOUT value, using default of 600 seconds"
            )
            self.APK_DECOMPILE_TIMEOUT = 600

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cleanup_run()

    def calculate_md5(self, input_str):
        """Calculate MD5 hash of a string."""
        return hashlib.md5(input_str.encode("utf-8")).hexdigest()

    def cleanup_run(self):
        """Clean up after analysis."""
        try:
            if self.analyzer:
                self.analyzer.cleanup()
                self.analyzer = None
            gc.collect()
        except Exception as e:
            self.log.error(f"Error in cleanup: {e}")

    def analyze_apk(self) -> Optional[Dict[str, Any]]:
        """Run APK code analysis and return results."""
        self.log.debug("Starting APK code analysis")
        try:
            self.analyzer = APKCodeAnalyzer(
                filepath=self.filepath,
                timeout=self.APK_DECOMPILE_TIMEOUT,
                log=self.log,
                decompile_modules=self.decompile_modules,
            )
            results = self.analyzer.extract()
            return results
        except Exception as e:
            self.log.error(f"Error in APK code analysis: {e}")
            import traceback
            self.log.error(f"Traceback: {traceback.format_exc()}")
            return None
        finally:
            self.cleanup_run()

    def extract(self):
        """Extract and process all analysis results.

        Uses daemon thread with timeout, same pattern as DecompileBinja.
        """
        self.log.debug(inspect.currentframe().f_code.co_name)

        extraction_completed = False
        extraction_result = False
        extraction_error = None

        def do_extraction():
            nonlocal extraction_completed, extraction_result, extraction_error
            try:
                results = self.analyze_apk()
                if not results:
                    extraction_result = False
                else:
                    self.analysis_results = results
                    self.analysis_results["sha256"] = self.sha256
                    self.analysis_results["sha1"] = self.sha1
                    self.analysis_results["md5"] = self.md5
                    extraction_result = True
            except Exception as e:
                extraction_error = e
                extraction_result = False
            finally:
                extraction_completed = True

        extraction_thread = threading.Thread(target=do_extraction)
        extraction_thread.daemon = True
        extraction_thread.start()

        start_time = time.time()
        while (
            not extraction_completed
            and (time.time() - start_time) < self.APK_DECOMPILE_TIMEOUT
        ):
            time.sleep(1)

        if not extraction_completed:
            self.log.error(
                f"APK extraction timed out after {self.APK_DECOMPILE_TIMEOUT} seconds"
            )
            self.cleanup_run()
            return None

        if extraction_error:
            self.log.error(f"Error in APK extraction: {extraction_error}")
            return None

        return self.analysis_results if extraction_result else None

    def prepare_export_data(self, exporter_type: str) -> Any:
        """Prepare data for database export."""
        self.log.debug(inspect.currentframe().f_code.co_name)
        if not self.analysis_results:
            return None

        if exporter_type == "ClickHouseExporter":
            now = datetime.now(timezone.utc)
            export = {"multi_table": True}

            # Table 1: Decompiled method content
            if self.analysis_results.get("decompiled_content"):
                export["decompiled_content"] = {
                    "table": "code_apk_decompiled_methods_content",
                    "data": [
                        [
                            f["decompiled_method_hash"],
                            f["decompiled_method"],
                            f.get("decompiled_method_type", "UNKNOWN"),
                            1 if f.get("decompiled_has_string_encryption") else 0,
                            1 if f.get("decompiled_has_reflection_calls") else 0,
                            1 if f.get("decompiled_excessive_goto_count") else 0,
                            now,
                        ]
                        for f in self.analysis_results["decompiled_content"]
                    ],
                    "column_names": [
                        "decompiled_method_hash",
                        "decompiled_method",
                        "decompiled_method_type",
                        "decompiled_has_string_encryption",
                        "decompiled_has_reflection_calls",
                        "decompiled_excessive_goto_count",
                        "analysis_date",
                    ],
                    "column_type_names": [
                        "FixedString(64)",
                        "String",
                        "Enum8('USER'=1, 'LIBRARY'=2, 'UNKNOWN'=5)",
                        "UInt8",
                        "UInt8",
                        "UInt8",
                        "DateTime64(3, 'UTC')",
                    ],
                }

            # Table 2: Decompiled method references
            if self.analysis_results.get("decompiled_refs"):
                export["decompiled_refs"] = {
                    "table": "code_apk_decompiled_methods_references",
                    "data": [
                        [
                            self.analysis_results["sha256"],
                            f["decompiled_method_hash"],
                            f.get("smali_method_hash"),
                            f.get("decompiled_class_name", ""),
                            f.get("decompiled_method_name", ""),
                            f.get("decompiled_method_signature", ""),
                            f.get("decompiled_method_prototype", ""),
                            f.get("functions_caller", []),
                            f.get("functions_call", []),
                            now,
                        ]
                        for f in self.analysis_results["decompiled_refs"]
                    ],
                    "column_names": [
                        "sha256",
                        "decompiled_method_hash",
                        "smali_method_hash",
                        "decompiled_class_name",
                        "decompiled_method_name",
                        "decompiled_method_signature",
                        "decompiled_method_prototype",
                        "functions_caller",
                        "functions_call",
                        "analysis_date",
                    ],
                    "column_type_names": [
                        "FixedString(64)",
                        "FixedString(64)",
                        "Nullable(FixedString(64))",
                        "LowCardinality(String)",
                        "LowCardinality(String)",
                        "String",
                        "String",
                        "Array(String)",
                        "Array(String)",
                        "DateTime64(3, 'UTC')",
                    ],
                }

            # Table 3: Smali method content
            if self.analysis_results.get("smali_content"):
                export["smali_content"] = {
                    "table": "code_apk_smali_methods_content",
                    "data": [
                        [
                            f["smali_method_hash"],
                            f["smali_method"],
                            f.get("smali_method_type", "UNKNOWN"),
                            f.get("smali_instructions_count", 0),
                            f.get("smali_register_count", 0),
                            1 if f.get("smali_has_string_encryption") else 0,
                            1 if f.get("smali_has_reflection_calls") else 0,
                            1 if f.get("smali_excessive_goto_count") else 0,
                            f.get("smali_flattened_score", 0.0),
                            f.get("smali_mba_score", 0.0),
                            now,
                        ]
                        for f in self.analysis_results["smali_content"]
                    ],
                    "column_names": [
                        "smali_method_hash",
                        "smali_method",
                        "smali_method_type",
                        "smali_instructions_count",
                        "smali_register_count",
                        "smali_has_string_encryption",
                        "smali_has_reflection_calls",
                        "smali_excessive_goto_count",
                        "smali_flattened_score",
                        "smali_mba_score",
                        "analysis_date",
                    ],
                    "column_type_names": [
                        "FixedString(64)",
                        "String",
                        "Enum8('USER'=1, 'LIBRARY'=2, 'UNKNOWN'=5)",
                        "UInt32",
                        "UInt16",
                        "UInt8",
                        "UInt8",
                        "UInt8",
                        "Float64",
                        "Float64",
                        "DateTime64(3, 'UTC')",
                    ],
                }

            # Table 4: Smali method references
            if self.analysis_results.get("smali_refs"):
                export["smali_refs"] = {
                    "table": "code_apk_smali_methods_references",
                    "data": [
                        [
                            self.analysis_results["sha256"],
                            f["smali_method_hash"],
                            f.get("decompiled_method_hash"),
                            f.get("smali_class_name", ""),
                            f.get("smali_method_name", ""),
                            f.get("smali_method_signature", ""),
                            now,
                        ]
                        for f in self.analysis_results["smali_refs"]
                    ],
                    "column_names": [
                        "sha256",
                        "smali_method_hash",
                        "decompiled_method_hash",
                        "smali_class_name",
                        "smali_method_name",
                        "smali_method_signature",
                        "analysis_date",
                    ],
                    "column_type_names": [
                        "FixedString(64)",
                        "FixedString(64)",
                        "Nullable(FixedString(64))",
                        "LowCardinality(String)",
                        "LowCardinality(String)",
                        "String",
                        "DateTime64(3, 'UTC')",
                    ],
                }

            # Table 5: Method similarity metrics (content-based fuzzy matching)
            if self.analysis_results.get("similarity_metrics"):
                export["method_similarity_metrics"] = {
                    "table": "code_apk_method_similarity_metrics",
                    "data": [
                        [
                            f["smali_method_hash"],
                            f.get("ssdeep_smali"),
                            f.get("tlsh_smali"),
                            f.get("ssdeep_smali_normalized"),
                            f.get("tlsh_smali_normalized"),
                            f.get("minhash", []),
                            now,
                        ]
                        for f in self.analysis_results["similarity_metrics"]
                    ],
                    "column_names": [
                        "smali_method_hash",
                        "ssdeep_smali",
                        "tlsh_smali",
                        "ssdeep_smali_normalized",
                        "tlsh_smali_normalized",
                        "minhash",
                        "analysis_date",
                    ],
                    "column_type_names": [
                        "FixedString(64)",
                        "Nullable(String)",
                        "Nullable(FixedString(72))",
                        "Nullable(String)",
                        "Nullable(FixedString(72))",
                        "Array(UInt8)",
                        "DateTime64(3, 'UTC')",
                    ],
                }

            # Table 5b: CFG method features (structural/topological)
            if self.analysis_results.get("cfg"):
                export["cfg_methods"] = {
                    "table": "code_apk_cfg_methods",
                    "data": [
                        [
                            cfg["smali_method_hash"],
                            cfg["cfg_topology_hash"],
                            cfg["block_count"],
                            cfg["edge_count"],
                            cfg.get("cfg_instructions_count", 0),
                            cfg.get("call_count", 0),
                            cfg["cyclomatic_complexity"],
                            cfg.get("loop_count", 0),
                            cfg.get("max_depth", 0),
                            cfg.get("max_fan_out", 0),
                            cfg.get("md_index_topdown", 0),
                            cfg.get("md_index_bottomup", 0),
                            cfg.get("prime_product_smali", 0),
                            cfg.get("cfg_feature_tlsh"),
                            cfg.get("wl_minhash", []),
                            cfg.get("bb_features", []),
                            cfg.get("cfg_adjacency", []),
                            now,
                        ]
                        for cfg in self.analysis_results["cfg"]
                        if cfg is not None
                    ],
                    "column_names": [
                        "smali_method_hash",
                        "cfg_topology_hash",
                        "block_count",
                        "edge_count",
                        "cfg_instructions_count",
                        "call_count",
                        "cyclomatic_complexity",
                        "loop_count",
                        "max_depth",
                        "max_fan_out",
                        "md_index_topdown",
                        "md_index_bottomup",
                        "prime_product_smali",
                        "cfg_feature_tlsh",
                        "wl_minhash",
                        "bb_features",
                        "cfg_adjacency",
                        "analysis_date",
                    ],
                    "column_type_names": [
                        "FixedString(64)",
                        "FixedString(16)",
                        "UInt16",
                        "UInt16",
                        "UInt32",
                        "UInt16",
                        "UInt16",
                        "UInt16",
                        "UInt16",
                        "UInt16",
                        "UInt64",
                        "UInt64",
                        "UInt64",
                        "Nullable(FixedString(72))",
                        "Array(UInt8)",
                        "Array(Array(UInt16))",
                        "Array(UInt32)",
                        "DateTime64(3, 'UTC')",
                    ],
                }

            # Table 6: Strings — reuse code_binja_strings_raw for cross-format correlation
            # DEX strings are MUTF-8; string_raw = string since no encoding difference
            if self.analysis_results.get("strings"):
                export["strings_raw"] = {
                    "table": "code_binja_strings_raw",
                    "data": [
                        [
                            self.analysis_results["sha256"],
                            s["string"],
                            s["string"],  # string_raw = string (MUTF-8 decoded to UTF-8)
                            s.get("string_encoding", "UTF8"),
                            s.get("string_offset", 0),
                            s.get("string_length", len(s["string"])),
                            s.get("string_length", len(s["string"])),  # string_raw_length = string_length
                            s.get("string_entropy", 0.0),
                        ]
                        for s in self.analysis_results["strings"]
                    ],
                    "column_names": [
                        "sha256",
                        "string",
                        "string_raw",
                        "string_encoding",
                        "string_offset",
                        "string_length",
                        "string_raw_length",
                        "string_entropy",
                    ],
                    "column_type_names": [
                        "FixedString(64)",
                        "String",
                        "String",
                        "LowCardinality(String)",
                        "UInt64",
                        "UInt32",
                        "UInt32",
                        "Float32",
                    ],
                }

            # Table 7: Analysis errors
            if self.analysis_results.get("analysis_errors"):
                export["analysis_errors"] = {
                    "table": "code_apk_analysis_errors",
                    "data": [
                        [
                            self.analysis_results["sha256"],
                            f.get("class_name"),
                            f.get("method_name"),
                            f.get("error_location", "unknown"),
                            f.get("error_message", ""),
                            f.get("error_type", "unknown"),
                            self.calculate_md5(
                                f"{f.get('error_message', '')}"
                                f"{f.get('class_name', '')}"
                                f"{f.get('method_name', '')}"
                                f"{f.get('error_location', 'unknown')}"
                            ),
                            "new",
                            now,
                        ]
                        for f in self.analysis_results["analysis_errors"]
                    ],
                    "column_names": [
                        "sha256",
                        "class_name",
                        "method_name",
                        "error_location",
                        "error_message",
                        "error_type",
                        "error_hash",
                        "status",
                        "analysis_date",
                    ],
                    "column_type_names": [
                        "FixedString(64)",
                        "Nullable(String)",
                        "Nullable(String)",
                        "LowCardinality(String)",
                        "Nullable(String)",
                        "Nullable(String)",
                        "FixedString(32)",
                        "Enum8('new'=1, 'investigating'=2, 'fixed'=3, 'wontfix'=4)",
                        "DateTime64(3, 'UTC')",
                    ],
                }

            return export

        return None

    def tag(self) -> str:
        """Return the tag for this extractor."""
        return Tag.APK_DECOMPILED.value

    def get_clickhouse_table(self) -> str:
        """Not used directly as we're handling multiple tables."""
        pass