package com.dphms.netguard

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class ScannerFragment : Fragment() {

    private lateinit var output: TextView
    private lateinit var progressBar: ProgressBar
    private lateinit var recyclerView: RecyclerView
    private val results = mutableListOf<ScanResult>()
    private lateinit var adapter: ScanResultAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        return inflater.inflate(R.layout.tab_scanner, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        output = view.findViewById(R.id.tvScanStatus)
        progressBar = view.findViewById(R.id.scanProgress)
        recyclerView = view.findViewById(R.id.scanResults)
        adapter = ScanResultAdapter(results)
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = adapter

        view.findViewById<Button>(R.id.btnScanAll).setOnClickListener {
            Thread { runScan("all") }.start()
        }

        view.findViewById<Button>(R.id.btnScanDangerous).setOnClickListener {
            Thread { runScan("dangerous") }.start()
        }

        view.findViewById<Button>(R.id.btnScanOverlay).setOnClickListener {
            Thread { runScan("overlay") }.start()
        }

        view.findViewById<Button>(R.id.btnScanUnknown).setOnClickListener {
            Thread { runScan("unknown") }.start()
        }
    }

    private fun runScan(type: String) {
        activity?.runOnUiThread {
            results.clear()
            adapter.notifyDataSetChanged()
            progressBar.visibility = View.VISIBLE
            progressBar.progress = 0
            output.text = "// Scanning... please wait"
        }

        val service = ShizukuManager.getService()
        if (service == null) {
            activity?.runOnUiThread {
                progressBar.visibility = View.GONE
                output.text = "// ERROR: Shizuku not ready. Start Shizuku and grant permission."
            }
            return
        }

        val scanResults: Array<String> = when (type) {
            "all" -> service.scanAllApps()
            "dangerous" -> service.scanDangerousPermissions()
            "overlay" -> service.scanOverlayAbuse()
            "unknown" -> service.scanUnknownSources()
            else -> emptyArray()
        }

        for (result in scanResults) {
            val parts = result.split("|")
            if (parts.size >= 3) {
                val scanResult = ScanResult(
                    pkg = parts[0],
                    severity = parts[1],
                    permissions = if (parts.size > 3) parts[3].split(",").filter { it.isNotBlank() } else emptyList(),
                    details = parts[2]
                )
                results.add(scanResult)
                activity?.runOnUiThread { adapter.notifyItemInserted(results.size - 1) }
            }
        }

        activity?.runOnUiThread {
            progressBar.visibility = View.GONE
            val label = when (type) {
                "all" -> "Full scan"
                "dangerous" -> "Dangerous permissions scan"
                "overlay" -> "Overlay/accessibility scan"
                "unknown" -> "Unknown sources scan"
                else -> "Scan"
            }
            output.text = "// $label complete. ${results.size} apps flagged. Results below."
        }
    }
}

data class ScanResult(
    val pkg: String,
    val severity: String,
    val permissions: List<String>,
    val details: String
)
