#!/usr/bin/env python3
import socket
import sys
import urllib.request
import json

def get_local_ips():
    ips = set(['127.0.0.1', '::1'])
    try:
        # Get all interfaces info
        for info in socket.getaddrinfo(socket.gethostname(), None):
            ips.add(info[4][0])
    except:
        pass

    # Another way to get common local IP
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ips.add(s.getsockname()[0])
        s.close()
    except:
        pass
    return ips

def is_port_open(host, port, timeout=2):
    try:
        with socket.create_connection((host, port), timeout=timeout):
            return True
    except:
        return False

def check_json_4141(host, timeout=2):
    url = f"http://{host}:4141"
    try:
        with urllib.request.urlopen(url, timeout=timeout) as response:
            content_type = response.headers.get('Content-Type', '')
            if 'application/json' in content_type:
                return True
            # Fallback check if it's valid JSON even without header
            data = response.read().decode('utf-8')
            json.loads(data)
            return True
    except:
        return False

def main():
    target_host = "server"
    target_codename = "remote"
    local_ips = get_local_ips()
    return_host = ""
    default_host = "/usr/share/doc/traduia/not-available.html" 
    return_codename = ""
    default_codename = "not-available"
    try:
        remote_ip = socket.gethostbyname(target_host)
        is_resolvable = True
    except socket.gaierror:
        is_resolvable = False
        remote_ip = None

    if is_resolvable and remote_ip:
        if remote_ip in local_ips:
            return_host = "localhost"
            return_codename = "local"
        else:
            return_host = target_host
            return_codename = target_codename
        
        if is_port_open(return_host, 4141) and check_json_4141(return_host):
            return_codename = f"{return_codename}+http"
        
        if not is_port_open(return_host, 8000):
            return_host = default_host

    if not return_host or "not-available" in return_host:
        return_host = f"file://{return_host}"
        return_codename = f"{return_codename}+{default_codename}"
    else:
        return_host = f"http://{return_host}"

    sys.stdout.write(f"{return_host}\n")
    sys.stderr.write(f"{return_codename}\n")

if __name__ == "__main__":
    main()
