from .imports import *
from .get_full_confs import *
from .bootstrap import bootstrap_domain
from .write_to_file import *
from .create_utils import *
PASSWORD = 'ANy1Kan@!23'


def create_lander(content_dir,**kwargs):
    path_mgr = get_path_mgr(*args,**kwargs)
    domain = path_mgr.domain
    root_content_path = path_mgr.root_content_path
    url_mgr = urlManager(domain)
    parsed = url_mgr.parsed
    name = parsed.get('app_name')
    meta_data = call_meta_data(**kwargs)

    
    lander = """<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />"""+f"""{meta_data}
  <style>
    body {{
      font-family: system-ui, sans-serif;
      margin: 0;
      padding: 2rem;
      background: #f9fafb;
      color: #111;
    }}
    h1 {{
      font-size: 2rem;
      margin-bottom: 1rem;
    }}
    a {{
      display: inline-block;
      margin: 0.5rem 0;
      font-size: 1.1rem;
      color: #2563eb;
      text-decoration: none;
    }}
    a:hover {{
      text-decoration: underline;
    }}
  </style>
</head>
<body>
  <h1>Welcome to {name}</h1>

</body>
</html>
"""

    write_to_file(contents = lander,file_path=root_content_path)
    return lander


def check_if_default_dir(directory):
    
    default_files = [os.path.join(directory,'index.conf'),os.path.join(directory,'index_http.conf')]
    dir_list = collect_globs(directories=[directory],user_at_host='solcatcher',password=PASSWORD).get('files')
    
    if len(dir_list) == 2 and default_files[0] in dir_list and default_files[1] in dir_list:
        return True
    return False
def create_pointers_index(domain,file_path):
    dirname = os.path.dirname(file_path)
 
    pointers_main_path = os.path.join(dirname,"main.conf")
    create_pointers_main(domain,pointers_main_path)
    contents = f"""#{file_path}
    include {pointers_main_path};"""
    write_to_file(contents=contents,file_path=file_path,user_at_host='solcatcher',password=PASSWORD)
def create_pointers_main(domain,file_path):
    filename,ext = os.path.splitext(domain)
    dirname = os.path.dirname(os.path.dirname(file_path))
    main_root_path = os.path.join(dirname,'main/root.conf')
    ext = ext.replace('.','')
    contents = f"""location / *^*
        include {main_root_path};
    ^*^
    # Serve the React SPA properly

    # Serve your imgs folder (unhashed public images)
    location /imgs/ *^*
        alias /mnt/24T/media/images/{filename}/;
        disable_symlinks off;
        access_log off;
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
    ^*^

    # Serve your Webpack static assets (JS/CSS/etc)
    location /static/ *^*
        alias /var/www/sites/{filename}/{ext}/react/main/build/static/;
        access_log off;
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
    ^*^"""

    print(f"pointers_main_path == {file_path}")
    write_to_file(contents=contents,file_path=file_path,user_at_host='solcatcher',password=PASSWORD)
def create_noncannonical_redirect_content(domain,file_path):
    contents = f"""# ----------------------------
# 2) Non-canonical HTTPS redirect
# ----------------------------
server *^*
    listen 443 ssl http2;
    server_name www.{domain} ;

    ssl_certificate     /etc/letsencrypt/live/{domain}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/{domain}/privkey.pem;
    include             /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam         /etc/letsencrypt/ssl-dhparams.pem;

    return 301 https://{domain}$request_uri;
^*^"""
    write_to_file(contents=contents,file_path=file_path,user_at_host='solcatcher',password=PASSWORD)
def create_server_name_content(domain,file_path):
    contents = f"""    server_name {domain} www.{domain};"""
    write_to_file(contents=contents,file_path=file_path,user_at_host='solcatcher',password=PASSWORD)
def create_ssl_content(domain,file_path):
    contents = f"""ssl_certificate /etc/letsencrypt/live/{domain}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/{domain}/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;"""
    write_to_file(contents=contents,file_path=file_path,user_at_host='solcatcher',password=PASSWORD)
def create_root_content(file_path,**kwargs):
    domain = kwargs.get('domain')
    filename,ext = os.path.splitext(domain)
    ext = ext.replace('.','')
    root_content_dir = f'/var/www/sites/{filename}/{ext}/html/'
    
    contents = f"""root {root_content_dir};
    index index.html;"""
    
    write_to_file(contents=contents,file_path=file_path,user_at_host='solcatcher',password=PASSWORD)
def create_main_index_contents(**kwargs):
    directory = kwargs.get('directory')
    domain = kwargs.get('domain')
    parent_index_path = os.path.join(directory,'index.conf')
    main_dir = os.path.join(directory,'main')
    print(main_dir)
    
       

    make_dirs(path=main_dir,user_at_host='solcatcher',password=PASSWORD)
    noncannonical_redirect_path = os.path.join(main_dir,'noncannonical-redirect.conf')
    create_noncannonical_redirect_content(domain,noncannonical_redirect_path)
    server_name_path = os.path.join(main_dir,'server_name.conf')
    create_server_name_content(domain,server_name_path)
    ssl_path = os.path.join(main_dir,'ssl.conf')
    create_ssl_content(domain,ssl_path)
    root_path = os.path.join(main_dir,'root.conf')
    create_root_content(root_path,**kwargs)
    pointers_dir = os.path.join(directory,'pointers')
    make_path(pointers_dir,user_at_host='solcatcher',password=PASSWORD)
    pointers_index_path = os.path.join(pointers_dir,"index.conf")
    create_pointers_index(domain,pointers_index_path)
    main_index_contents  = f"""# HTTP redirect to HTTPS
server *^*
    include /etc/nginx/sites-available/common/listen_80.conf;
    include {server_name_path};
    include /etc/nginx/sites-available/common/301_return.conf;
^*^

# HTTPS server
server *^*
    include /etc/nginx/sites-available/common/listen_443.conf;
    include {server_name_path};
    include {root_path};
    include {ssl_path};
    include {pointers_index_path};

^*^
"""
    write_to_file(contents = main_index_contents,file_path = parent_index_path,user_at_host='solcatcher',password=PASSWORD)
    

def check_and_back(**kwargs):
        directory = kwargs.get('directory')
        domain = kwargs.get('domain')
        index_path = os.path.join(directory,'index.conf')
        
        result = get_full_confs(filename=None, file_path='/etc/nginx/sites-available/ireadsolidity/biz/index.conf',user_at_host='solcatcher',password='ANy1Kan@!23')
        domain= domain or result.split('server_name ')[1].split(' www.')[0]
        #contents = read_from_file(index_path)#)#)#,user_at_host='solcatcher',password=PASSWORD)
        #print(contents)

        back_path = os.path.join(directory,'index.conf.bak')
        #copy_files(index_path,back_path)#,user_at_host='solcatcher',password=PASSWORD)
        print(f"index_path ==> {back_path}")
        endpoints_dir = os.path.join(directory,'endpoints')
        pointers_dir = os.path.join(directory,'pointers')
        make_path(pointers_dir,user_at_host='solcatcher',password=PASSWORD)
        kwargs['domain']=domain
        create_main_index_contents(**kwargs)
        filename,ext = os.path.splitext(domain)
        root_content_dir = f'/var/www/sites/{filename}/{ext}/html/'
        bootstrap_domain(root_content_dir,**kwargs)

