"""
This file will handle security aspects associated with QCMS
"""

import typer
from typing_extensions import Annotated
from typing import Optional
from typing import Tuple
import os
import json
import plugin_ix as px
from enum import Enum
import pandas as pd
from rich.table import Table
from rich import print
import uuid
import cms
import requests


FAILED = '[ [red] \u2717 [/red] ]'
PASSED = '[ [green] \u2713 [/green] ]'
cli = typer.Typer()


@cli.command(name="set-key")
def set_key (manifest:Annotated[str,typer.Argument(help="path to manifest or manifest folder")],
            keyfile:Annotated[str,typer.Argument(help="path of the key file to generate")]
            ):
    """
    force-reload of an application
    """
    keyfile = cms.engine.config.get_manifest(keyfile)
    if not os.path.exists(keyfile):
        f = open(keyfile,'w')
        f.write(str(uuid.uuid4()))
        f.close()
        #
        manifest = cms.engine.config.get_manifest(manifest)
        _config = cms.engine.config.get(manifest)
        if 'source' not in _config['system']:
            _config['system']['source'] = {'id':'disk'}
        _config['system']['source']['key'] = os.path.abspath(keyfile)
        cms.engine.config.write(_config,manifest)
        _msg = f"""{PASSED} [bold]{_config['layout']['header']['title']}[/bold] : A key was generated and written to {keyfile}
            use this key in header to enable reload of the site ...
        """
    else:
        _msg = f"""{FAILED} [bold]{_config['system']['layout']['header']['title']}[/bold] : could [bold]NOT[/bold] generate a key, because it would seem you already have one
            Please manually delete {keyfile}

            
        """
    print (_msg)
@cli.command (name='reload')
def reload (
    path:Annotated[str,typer.Argument(help="")],
    port:int=typer.Option(default=None,help="port of the host to call")
    ) :
    """
    Reload a site/portal given the manifest ...
    """
    path = cms.engine.config.get_manifest(path)
    _config = cms.engine.config.get( path)
    if 'source' in _config['system'] and 'key' in _config['system']['source'] :
        _spath = _config['system']['source']['key']
        # f = open(_config['system']['source']['key'])
        if not os.path.exists(_spath) :
            mpath = path.split(os.sep)[:-1] + _spath.split(os.sep)
            _spath = os.sep.join(mpath)
            pass
        
        f  = open(_spath)
        key = f.read()
        f.close()
        
        _port = port if port else _config['system']['app']['port']
        url = f"http://localhost:{_port}/reload"
        resp = requests.post(url, headers={"key":key})
        if resp.status_code == 200 :
            _msg = f"""{PASSED} [bold]{_config['layout']['header']['title']}[/bold] : successfully reloaded {url}"""
        else:
            _msg = f"""{FAILED} failed to reload, status code {resp.status_code}\n{url}
            """
    else:
        _msg = f"""{FAILED} no secure key found in manifest to request reload"""
    print (_msg)

