import nmap
import pandas as pd
from datetime import datetime
import os

# Set up data directory
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, "..", "data"))
os.makedirs(DATA_DIR, exist_ok=True)


def detailed_scan():
    active_hosts_path = os.path.join(DATA_DIR, "active_hosts.csv")
    try:
        active_hosts_df = pd.read_csv(active_hosts_path)
    except FileNotFoundError:
        print("File active_hosts.csv not found. Please run the network discovery script first.")
        return

    nm = nmap.PortScanner()
    scan_results = []

    start_time = datetime.now()
    print(f"Scan started at: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")

    for index, row in active_hosts_df.iterrows():
        ip = row['IP']
        print(f"Scanning {ip} for detailed information...")
        try:
            nm.scan(ip, arguments='-p- -T5')
        except Exception as e:
            print(f"Error scanning {ip}: {e}")
            continue

        for host in nm.all_hosts():
            hostnames = [x['name'] for x in nm[host].get('hostnames', [])]
            mac_address = nm[host]['addresses'].get('mac', 'N/A')
            scan_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            for proto in nm[host].all_protocols():
                for port in nm[host][proto]:
                    port_data = nm[host][proto][port]
                    if port_data.get('state') != 'open':
                        continue

                    row = [
                        ip,
                        ', '.join(hostnames),
                        mac_address,
                        proto,
                        port,
                        port_data.get('name', ''),
                        port_data.get('state', ''),
                        port_data.get('product', ''),
                        port_data.get('version', ''),
                        port_data.get('extrainfo', ''),
                        scan_timestamp
                    ]
                    scan_results.append(row)

    end_time = datetime.now()
    print(f"Scan finished at: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"Total scan duration: {end_time - start_time}")

    if not scan_results:
        print("No open ports found.")
        return

    columns = [
        'IP', 'Hostname', 'MAC Address', 'Protocol', 'Port', 'Name',
        'State', 'Product', 'Version', 'Extra Info', 'Timestamp'
    ]
    detailed_df = pd.DataFrame(scan_results, columns=columns)

    filename = "detailed_scan_results.csv"
    output_file = os.path.join(DATA_DIR, filename)
    write_header = not os.path.exists(output_file)
    detailed_df.to_csv(output_file, mode='a', header=write_header, index=False)
    print(f"Scan results saved to {output_file}")
    print(detailed_df)

if __name__ == "__main__":
    detailed_scan()