import logging
import os
from datetime import datetime
from typing import Dict, List

logger = logging.getLogger(__name__)

MATCH_CONFIG_CSV_PATH = "match_config_csv"


class OutputService:
    def __init__(self, crawl_out_path: str = None, matched_path: str = None):
        self.crawl_out_path = MATCH_CONFIG_CSV_PATH if crawl_out_path is None else crawl_out_path
        self.matched_path = matched_path

    def is_valid_crawl_output(self, code: str, date: datetime) -> bool:
        file_path = os.path.join(MATCH_CONFIG_CSV_PATH, f"{code}-{date.strftime('%Y-%m-%d')}.txt")
        exists = os.path.isfile(file_path)
        if not exists:
            logger.warning(f"Crawl output not found: {file_path}")
        return exists

    def load_retailer_output(self, code: str, date: datetime) -> List[str]:
        file_path = os.path.join(MATCH_CONFIG_CSV_PATH, f"{code}-{date.strftime('%Y-%m-%d')}.txt")
        lines = []
        try:
            with open(file_path, encoding="utf-8") as f:
                lines = [line.strip() for i, line in enumerate(f) if i > 0 and line.strip()]
        except FileNotFoundError:
            logger.warning(f"File not found: {file_path}")
        except Exception as e:
            logger.error(f"Error reading file {file_path}: {e}")
        return lines

    def load_histories(self, history_file_name: str) -> Dict[str, str]:
        file_path = os.path.join(MATCH_CONFIG_CSV_PATH, f"{history_file_name}-history.txt")
        history_map = {}
        try:
            with open(file_path, encoding="utf-8") as f:
                for line in f:
                    parts = line.strip().split("||")
                    if len(parts) == 2:
                        history_map[parts[1].strip()] = parts[0].strip()
        except FileNotFoundError:
            logger.warning(f"History file not found: {file_path}")
        except Exception as e:
            logger.error(f"Error loading history file: {e}")
        return history_map

    def save_matched_to_file(code: str, content: str, date: datetime, run_keyword: bool):
        prefix = "keyword" if run_keyword else "history"
        file_name = f"{prefix}/{code}-{date.strftime('%Y-%m-%d')}-matched.txt"
        file_path = os.path.join(MATCH_CONFIG_CSV_PATH, file_name)
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        try:
            with open(file_path, "w", encoding="utf-8") as f:
                f.write(content)
            logger.info(f"Saved matched output: {file_path}")
        except Exception as e:
            logger.error(f"Failed to write matched output: {e}")
