#!/usr/pkg/bin/python3.11
# -*- coding: utf-8 -*-
#

#  Copyright (C) 2015-2016, 2018 Rafael Senties Martinelli
#
#  This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License 3 as published by
#   the Free Software Foundation.
#
#  This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software Foundation,
#   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA.


__version__ = "2018.10.28"

MESUREMENT_2DIGIT_UNITS = ('em','ex','px','cm','mm','in','pt','pc','ch','vh','vw')
TAB_CHARACTER="    "

def replace_multiple_spaces(text):
    return ' '.join(text.split())


def inside_closing_brace(start_index, text, end_index=-1):
    
    if end_index == -1:
        end_index = len(text)
    
    reserch_text = text[start_index:end_index]
    
    if "}" in reserch_text and not "{" in reserch_text.split("}",1)[0]:
        return True
        
    return False

def format_line_with_left_code_and_right_comment(original_line, coment_separator):

    code_block = original_line.split(coment_separator,1)[0]
    comment_block = original_line.split(coment_separator,1)[1]
    
    code_block = replace_multiple_spaces(code_block)
    new_line = code_block + coment_separator + comment_block + '\n'
    new_line = new_line.replace(';'+coment_separator,'; '+coment_separator)
            
    return new_line


def format_line_with_left_comment_and_right_code(original_line, coment_separator):

    comment_block = original_line.split(coment_separator,1)[0]
    code_block = original_line.split(coment_separator,1)[1]
    
    code_block = replace_multiple_spaces(code_block)
    new_line = comment_block + coment_separator + '\n' + code_block
            
    return new_line


def format_coments_and_spaces(original_text):
    
    new_text = ""
    inside_comment = False
    
    for original_line in original_text.split('\n'):
        
        if '/*' in original_line and '*/' in original_line: # this will fail if the comment tags are inverted. To be improved.
            
            if original_line.rsplit('*/', 1)[1].strip() != '':
                new_text += format_line_with_left_comment_and_right_code(original_line, '*/')
            else:
                new_text += format_line_with_left_code_and_right_comment(original_line, '/*')
            
        elif '/*' in original_line:
            inside_comment = True
            
            code_text = original_line.split('/*',1)[0].strip()
            comment_text = original_line.split('/*',1)[1]
            
            if code_text == '':
            
                if new_text[-1:] != '\n':
                    new_text += '\n'
                
                new_text += original_line + '\n'
            else:
                new_text += code_text + '\n/*' + comment_text + '\n'
            
            
        elif inside_comment:
            
            if '*/' in original_line:
                inside_comment = False
                
                comment_text = original_line.rsplit('*/',1)[0]
                code_text = original_line.rsplit('*/',1)[1].strip()
                
                if code_text == '':
                    new_text += original_line + '\n\n'
                else:
                    new_text += comment_text+ '*/\n' + code_text
            else:
                new_text += original_line + '\n'
        
        elif '//' in original_line:
            new_text += format_line_with_left_code_and_right_comment(original_line, '//')
        
        else:
            
            new_line = original_line
            
            for char in ('\t','\n'):
                new_line=new_line.replace(char,'')
                
            new_line = replace_multiple_spaces(new_line)
            
            new_text += new_line
        
    return new_text


def needs_space_before(new_text_last_char, char, chars):

    if new_text_last_char in (' ',':'):
        return False
    
    elif char == '#' and chars[-1] == ':':
        return True
    
    elif char == '.' and not chars[-1].isdigit() and chars[1].isdigit():
        return True
    
    elif char == '!' and ''.join(chars[x] for x in range(1,4)) == 'imp':
        return True
    
    return False

def needs_space_after(char, char_index, chars, text):

    if chars[1] in (';',' '):
        return False

    elif char in (',',')'):
        return True

    elif char == ':' and inside_closing_brace(char_index, text):
        return True
    
    elif char == 's' and chars[-1].isdigit() and not chars[1]+chars[2]=='ol':
        return True
        
    elif chars[-1]+char in MESUREMENT_2DIGIT_UNITS and chars[-2].isdigit():
        return True

    elif char == 'm' and chars[-3].isdigit() and ''.join(chars[x] for x in range(-2,1)) == 'rem':
        return True
        
    elif char in ('n','x') and chars[-4].isdigit() and ''.join(chars[x] for x in range(-3,1)) in ('vmin','vmax'):
        return True
        
    return False
    
    
def decompress_css(original_css):
    
    converted_css = format_coments_and_spaces(original_css)
    
    new_text=""
    indent_level=0
    inside_commented_block = False
    

    for i, char in enumerate(converted_css):
        
        #
        #
        #
        chars={k:'' for k in range(-4,4)}
        for k in range(-4,4):
            try:
                chars[k]=converted_css[i+k]
            except:
                pass
        
        new_text_last_char=new_text[-1:]
        
        
        #
        #
        #
        if (char == '/' and chars[1] == '*') or inside_commented_block:
            inside_commented_block = True
             
            if char == '/' and chars[-1] == '*':
                inside_commented_block = False
                
        elif char in ('>', '+'):
            
            if chars[-1] != ' ':
                char = ' '+char
            
            if chars[1] != ' ':
                char = char + ' '
        
        elif needs_space_after(char, i, chars, converted_css):
            char+=' '
        
        elif needs_space_before(new_text_last_char, char, chars):
            char = ' '+char
    
        elif char == '{':
            
            indent_level+=1
            
            if new_text_last_char != ' ':
                char =' {\n'
            else:
                char ='{\n'
            
            
        elif char == '}':
            
            indent_level-=1
            
            if new_text_last_char != '\n':
                new_text += '\n'
                new_text_last_char='\n'
            
            if chars[1] == '}':
                char = '}\n'
            else:
                char = '}\n\n'
            
            
        elif char == ';':
            
            if chars[2] == '/' and chars[3] == '*':  #     code; /* comment */
                pass
            elif chars[2] == '/' and chars[3] == '/': #    code; // comment
                pass
            else:   
                char = ';\n'
        
        
        if new_text_last_char == '\n':
            new_text += TAB_CHARACTER*indent_level
            
        new_text+=char

    return new_text


_CSS_TO_TEST="""
/*
    TESTING COMMENT BLOCK

 Copyright (C) 2018 Rafael Senties Martinelli
     This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
     This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR a PARTICULAR PURPOSE. See the GNU General Public License for more details.
    You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.


*/

// TESTING COMMENTS
.code, .command {
    padding-left: 0.5em;/* ONE LINE COMMENT IN BLOCK  */
    padding-right: 0.5em;// THIS IS ALSO A ONE LINE COMMENT
    background-color: #E8E8E8;color: black;}/*
  Testing decompression
*/

.end-text {  margin-top: 3em;font-size: .9em;font-weight: normal}
.end-text+.end-text{margin-top:-.5em;}
div.c-window {position: relative;border-radius: .5em;padding-bottom: .05em;margin-bottom: 1em;border: .5px solid black;} div.c-window > div {padding-left: 0.5em;font-weight: bold;border-top-left-radius: .5em;border-top-right-radius: .5em;} div.c-window>div > span {float: right;color: white;margin-right: 1em;}
div.c-window pre {padding:.5em;margin-top:0em;overflow:auto;max-width: 100%}

div.root-terminal>div {background: #C91426;color: black;}div.root-terminal {background: black;color: white;}
div.textfile>div,div.terminal > div {background: #333333;color: #c7c7c7;}
div.terminal {background:black;color:white;}
div.textfile {
    background: white;
    color: black;
}

/* articles: libreware engineering */table.normal{vertical-align: top;background-color: #D3D2D7;text-align: center;float: left;margin-right: 1em;margin-bottom: 0.6em;}
table.normal > tbody > tr:first-child {font-weight: bold;}

/*
        Question divs:

      alienware-kbl/faq

*/.question {
    padding: .5em;
margin-bottom: .5em;
            color: black;border-radius: 1em;
    background: #BABABA}.question > div {padding-left: 1em;padding-right: 1em;}.question>div:first-child {cursor: pointer;}

.question > div:first-child > a {
    color: black;
}.question>div:first-child h2{margin-top: 0em;padding-bottom: 0em;margin-bottom: 0em;padding-top: 0em;}

.question > div:nth-child(2) {
text-align: left;
         padding-top: .2em;
    padding-bottom: .2em;border-bottom-left-radius: 1em;
border-bottom-right-radius: 1em;background: #E8E8E8;}.question .code {
    background: #BABABA;
}

/* add the li second numbers  ex: 1.1 */
ol {counter-reset: item}ol > li {                  counter-increment: item} ol > li > ol > li {
    display: block;
}ol>li >ol> li:before {
    content: counters(item, ".") ". ";
    margin-left
    
    
    : 
    
    
    -20px
    
    ;
    
    
    
    }

ol>li>ol>li> h3 {margin-top: -1.2em;
    margin-left: 1em}
    
/* code highlight */

.CHwords {color: #008504}                 .CHchars {color: #9B26A4;}.CHmwords {color: #0016A8;}
                .CHcwords {color: #6D0D61}
.CHdcomment {color: #686565;}
.CHlcomment1 {color: #7F7A7A;}.CHlcomment2 {color: #1C63A9}.CHscomment1{color:#844D01;}.CHscomment2{color:#AF9D00;}.CHnumb {color: #9C0000;}

@media print {
  html,body {max-width: 100%;width: 100%;padding:0;margin: 0;}header,
#feedbacks-form,
footer,#download-pdf-help{display: none;height:0;}
.code,
pre{color: green}
main{position:absolute;left: 0;top: 0;width: 100vw;max-width: 100vw;margin:0 !important;padding: 0 !important;}
a[href^="http"]:after{content: " (" attr(href) ") ";}
tr, td, th {page-break-inside:avoid}thead {display:table-header-group}}
"""


if __name__ == '__main__':
    
    import sys
     
    css=sys.stdin.read()
    css=decompress_css(css)
    sys.stdout.write(css)

