"""
Refactored CLI configuration generation to use config module.
This shows how to consolidate the CLI to use the shared config.
"""


def generate_full_conf_from_config(project_name: str) -> str:
    """Generate full inline configuration using the config module."""
    from .config import get_haive_config

    # Get the complete configuration from config module
    config = get_haive_config(project_name)

    # Start with the basic template
    lines = [
        f'''"""
Sphinx configuration for {project_name}.

This configuration includes all extensions from PyDevelop-Docs (43+ extensions).
Generated by pydvlp-docs init using shared configuration.
"""

import os
import sys
from datetime import date
from pydvlp_docs.config import get_haive_config

# -- Path setup --------------------------------------------------------------
sys.path.insert(0, os.path.abspath("../.."))

# -- Project information -----------------------------------------------------
project = "{project_name}"
copyright = f"{{date.today().year}}, {project_name} Team"
author = "{project_name} Team"
release = "0.1.0"

# -- Load configuration from pydvlp_docs.config --------------------------
# This ensures consistency between all configuration methods
config = get_haive_config(project)

# Apply all configuration settings
for key, value in config.items():
    if key not in ['project', 'copyright', 'author', 'release']:
        globals()[key] = value

# -- Additional setup --------------------------------------------------------

def setup(app):
    """Sphinx setup hook."""
    app.add_css_file("css/custom.css")
    app.add_js_file("js/api-enhancements.js")
'''
    ]

    return "\n".join(lines)


def generate_inline_full_conf(project_name: str) -> str:
    """
    Alternative: Generate full configuration by extracting values from config module
    and inlining them (no runtime import dependency).
    """
    import json

    from .config import get_haive_config

    # Get the complete configuration from config module
    config = get_haive_config(project_name)

    # Start with the basic template
    lines = [
        f'''"""
Sphinx configuration for {project_name}.

This configuration includes all extensions from PyDevelop-Docs (43+ extensions).
Generated by pydvlp-docs init with inline configuration.
"""

import os
import sys
from datetime import date

# -- Path setup --------------------------------------------------------------
sys.path.insert(0, os.path.abspath("../.."))

# -- Project information -----------------------------------------------------
project = "{project_name}"
copyright = f"{{date.today().year}}, {project_name} Team"
author = "{project_name} Team"
release = "0.1.0"

# -- Configuration from pydvlp_docs.config (inlined) ---------------------
'''
    ]

    # Process each configuration item
    for key, value in sorted(config.items()):
        if key in ["project", "copyright", "author", "release"]:
            continue

        # Handle different types appropriately
        if isinstance(value, str):
            if "\n" in value:
                # Multi-line string
                lines.append(f'{key} = """')
                lines.append(value)
                lines.append('"""')
            else:
                lines.append(f'{key} = "{value}"')

        elif isinstance(value, list):
            if len(value) == 0:
                lines.append(f"{key} = []")
            elif len(value) == 1:
                lines.append(f"{key} = [{repr(value[0])}]")
            else:
                lines.append(f"{key} = [")
                for item in value:
                    lines.append(f"    {repr(item)},")
                lines.append("]")

        elif isinstance(value, dict):
            if len(value) == 0:
                lines.append(f"{key} = {{}}")
            else:
                lines.append(f"{key} = {{")
                for k, v in value.items():
                    lines.append(f"    {repr(k)}: {repr(v)},")
                lines.append("}")

        elif isinstance(value, bool):
            lines.append(f"{key} = {value}")

        elif isinstance(value, (int, float)):
            lines.append(f"{key} = {value}")

        elif value is None:
            lines.append(f"{key} = None")

        else:
            # For other types, use repr
            lines.append(f"{key} = {repr(value)}")

        lines.append("")  # Empty line after each setting

    # Add the setup function
    lines.extend(
        [
            "",
            "def setup(app):",
            '    """Sphinx setup hook."""',
            '    if os.path.exists("_static/css/custom.css"):',
            '        app.add_css_file("css/custom.css")',
            '    if os.path.exists("_static/js/api-enhancements.js"):',
            '        app.add_js_file("js/api-enhancements.js")',
        ]
    )

    return "\n".join(lines)


# Example of how to update the CLI class
EXAMPLE_CLI_UPDATE = '''
# In cli.py, replace the _generate_full_conf method:

def _generate_full_conf(self) -> str:
    """Generate full inline configuration using the config module."""
    from .cli_refactor import generate_inline_full_conf
    return generate_inline_full_conf(self.project_name)

# This ensures:
# 1. No duplication of configuration
# 2. All fixes from config.py are included
# 3. Easy maintenance - update only config.py
# 4. Consistent behavior across all usage patterns
'''
