import json
import os

from constants import OutputFile
from logging_utils import setup_logger

logger = setup_logger(__name__, os.path.splitext(os.path.basename(__file__))[0])


def gen_proteases(output_file: str = OutputFile.PROTEASES) -> None:
    """Generate protease data file from JSON"""

    logger.info("\n" + "=" * 60)
    logger.info("GENERATING PROTEASE DATA")
    logger.info("=" * 60)

    logger.info("  📖 Reading from: ./data/proteases.json")
    with open("./data/proteases.json") as f:
        data = json.load(f)

    proteases_data = data["proteases"]
    logger.info(f"  ✓ Parsed {len(proteases_data)} proteases")

    logger.info(f"\n  📝 Writing to: {output_file}")

    # Generate StrEnum entries
    enum_entries: list[str] = []
    for protease_dict in proteases_data:
        protease_id = protease_dict["id"]
        # Convert id to uppercase enum name
        enum_name = protease_id.upper()
        enum_entries.append(f'    {enum_name} = "{protease_id}"')

    enum_str = "\n".join(enum_entries)

    # Generate Literal type entries
    literal_entries: list[str] = []
    for protease_dict in proteases_data:
        protease_id = protease_dict["id"]
        literal_entries.append(f'    "{protease_id}",')

    literal_str = "\n".join(literal_entries)

    # Generate the protease dictionary entries
    entries: list[str] = []
    for protease_dict in proteases_data:
        # Use single quotes for regex string
        regex_str = protease_dict["regex_pattern"]
        protease_id = protease_dict["id"]
        enum_name = protease_id.upper()

        entry = f'''Proteases.{enum_name}: ProteaseInfo(
    id=Proteases.{enum_name},
    name="{protease_dict["name"]}",
    full_name="{protease_dict["full_name"]}",
    regex='{regex_str}',
),'''
        entries.append(entry)

    entries_str = "\n".join(entries)

    # Write the complete file
    content = f'''"""Auto-generated protease data"""
# DO NOT EDIT - generated by gen_proteases_obo.py

from typing import Literal
from enum import StrEnum

from .dclass import ProteaseInfo

class Proteases(StrEnum):
    """Enum of protease IDs"""
{enum_str}

PROTEASE_LITERALS = Literal[
{literal_str}
]


PROTEASES_DICT: dict[Proteases, ProteaseInfo] = {{
{entries_str}
}}
'''

    with open(output_file, "w") as f:
        f.write(content)

    logger.info(f"✅ Successfully generated {output_file}")
    logger.info(f"   Total entries: {len(proteases_data)}")


if __name__ == "__main__":
    gen_proteases()
