"""
Snakemake script for writing final output files.

This script is called by the write_outputs rule.
"""

import os
import logging
import pandas as pd

from crisprdesigner2 import (
    write_outputs,
    load_predesigned_guides,
    merge_with_predesigned,
)

# Set up logging
logging.basicConfig(
    filename=snakemake.log[0],
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def main():
    logger.info("Starting output file generation")

    # Get inputs from snakemake
    guides_file = snakemake.input.guides
    predesigned_path = snakemake.params.predesigned
    output_dir = snakemake.params.output_dir

    logger.info(f"Input guides: {guides_file}")
    logger.info(f"Pre-designed guides: {predesigned_path or 'None'}")
    logger.info(f"Output directory: {output_dir}")

    # Read scored guides
    guides_df = pd.read_csv(guides_file, sep='\t')
    logger.info(f"Read {len(guides_df)} guides")

    # Filter to only passing guides for final output
    if 'passed_filters' in guides_df.columns:
        final_df = guides_df[guides_df['passed_filters'] == True].copy()
        logger.info(f"Keeping {len(final_df)} guides that passed filters")
    else:
        final_df = guides_df.copy()

    # Load and merge with pre-designed guides
    predesigned_df = load_predesigned_guides(predesigned_path)
    if not predesigned_df.empty:
        logger.info(f"Merging with {len(predesigned_df)} pre-designed guides")
        final_df = merge_with_predesigned(final_df, predesigned_df)
        logger.info(f"After merge: {len(final_df)} total guides")

    # Remove internal columns before final output
    columns_to_remove = ['filter_reason', 'passed_filters', '_region_name']
    for col in columns_to_remove:
        if col in final_df.columns:
            final_df = final_df.drop(columns=[col])

    # Write output files
    write_outputs(final_df, output_dir)

    # Verify outputs exist
    txt_file = os.path.join(output_dir, 'designGuides.txt')
    bed_file = os.path.join(output_dir, 'designGuides.bed')

    if os.path.exists(txt_file):
        logger.info(f"Created: {txt_file}")
    else:
        logger.error(f"Failed to create: {txt_file}")

    if os.path.exists(bed_file):
        logger.info(f"Created: {bed_file}")
    else:
        logger.error(f"Failed to create: {bed_file}")

    logger.info("Output file generation complete")


if __name__ == '__main__':
    main()
