from .base_strategy import BaseStrategy
from fetchers.factory import FetcherFactory
from analysis.cn_analyzer import CN_Analyzer
from reporting.cn_report_generator import CN_ReportGenerator
from storage.file_io import DataStorage
import os

class CN_Strategy(BaseStrategy):
    def __init__(self, stock_code, tushare_token):
        super().__init__(stock_code)
        self.tushare_token = tushare_token
        self.fetcher = FetcherFactory.get_fetcher('CN', self.tushare_token)
        self.analyzer = CN_Analyzer()
        self.reporter = CN_ReportGenerator()
        self.storage = DataStorage()
        self.raw_data = {}
        self.analysis_result = None

    def fetch_data(self):
        print(f"Fetching data for CN market, stock: {self.stock_code}")
        self.raw_data['income'] = self.fetcher.get_income_statement(self.stock_code)
        self.raw_data['balance'] = self.fetcher.get_balance_sheet(self.stock_code)
        self.raw_data['cashflow'] = self.fetcher.get_cash_flow(self.stock_code)
        self.raw_data['metrics'] = self.fetcher.get_market_metrics(self.stock_code)
        self.raw_data['dividends'] = self.fetcher.get_dividends(self.stock_code)
        self.raw_data['repurchases'] = self.fetcher.get_repurchases(self.stock_code)

        if not self.raw_data['income'].empty and 'date' in self.raw_data['income'].columns:
            dates = self.raw_data['income']['date'].tolist()
            historical_metrics = self.fetcher.get_historical_metrics(self.stock_code, dates)
            self.raw_data['historical_metrics'] = historical_metrics
            if historical_metrics is not None and not historical_metrics.empty:
                self.storage.save_data(historical_metrics, 'CN', self.stock_code, "historical_metrics")

    def analyze_data(self):
        print(f"Analyzing data for CN market, stock: {self.stock_code}")
        self.analysis_result = self.analyzer.process_data(
            self.raw_data['income'],
            self.raw_data['balance'],
            self.raw_data['cashflow'],
            self.raw_data['metrics'],
            self.raw_data.get('historical_metrics'),
            self.raw_data.get('dividends'),
            self.raw_data.get('repurchases')
        )
    def generate_report(self):
        print(f"Generating report for CN market, stock: {self.stock_code}")
        if self.analysis_result is not None and not self.analysis_result.empty:
            output_dir = os.path.join("data", 'CN', self.stock_code)
            self.reporter.generate_report(
                df_analysis=self.analysis_result,
                symbol=self.stock_code,
                market='CN',
                metrics=self.raw_data['metrics'],
                output_dir=output_dir
            )
        else:
            print("No analysis result to generate report.")
