import { devLog } from '../utils/logger.js';

class MyTischtennisUrlParserService {
  /**
   * Parse myTischtennis URL and extract configuration data
   * 
   * Example URL:
   * https://www.mytischtennis.de/click-tt/HeTTV/25--26/ligen/1.Kreisklasse/gruppe/504417/mannschaft/2995094/Harheimer_TC_(J11)/spielerbilanzen/gesamt
   * 
   * @param {string} url - The myTischtennis URL
   * @returns {Object} Parsed configuration data
   */
  parseUrl(url) {
    try {
      // Remove trailing slash if present
      url = url.trim().replace(/\/$/, '');

      // Try different URL patterns
      
      // Pattern 1: Team URL with mannschaft/{teamId}/{teamname}
      // /click-tt/{association}/{season}/{type}/{groupname}/gruppe/{groupId}/mannschaft/{teamId}/{teamname}/...
      const teamPattern = /\/click-tt\/([^\/]+)\/([^\/]+)\/([^\/]+)\/([^\/]+)\/gruppe\/([^\/]+)\/mannschaft\/([^\/]+)\/([^\/]+)/;
      
      // Pattern 2: Table/Group URL without team info
      // /click-tt/{association}/{season}/{type}/{groupname}/gruppe/{groupId}/tabelle/gesamt
      const tablePattern = /\/click-tt\/([^\/]+)\/([^\/]+)\/([^\/]+)\/([^\/]+)\/gruppe\/([^\/]+)\/tabelle\/([^\/]+)/;
      
      let match = url.match(teamPattern);
      let isTeamUrl = true;
      
      if (!match) {
        match = url.match(tablePattern);
        isTeamUrl = false;
      }
      
      if (!match) {
        throw new Error('URL format not recognized. Expected formats:\n' +
          '- Team URL: /click-tt/{association}/{season}/{type}/{groupname}/gruppe/{groupId}/mannschaft/{teamId}/{teamname}/...\n' +
          '- Table URL: /click-tt/{association}/{season}/{type}/{groupname}/gruppe/{groupId}/tabelle/gesamt');
      }

      const [
        ,
        association,
        seasonRaw,
        type,
        groupnameEncoded,
        groupId,
        ...rest
      ] = match;

      // Decode and process values
      const seasonShort = seasonRaw.replace('--', '/'); // "25--26" -> "25/26"
      const season = this.convertToFullSeason(seasonShort); // "25/26" -> "2025/2026"
      const groupnameDecoded = this.decodeGroupName(groupnameEncoded);

      const result = {
        association,
        season,
        seasonShort, // Für API-Calls
        type,
        groupname: groupnameDecoded, // Dekodierte Version für Anzeige
        groupnameOriginal: groupnameEncoded, // Originale URL-kodierte Version
        groupId,
        originalUrl: url,
        urlType: isTeamUrl ? 'team' : 'table'
      };

      if (isTeamUrl) {
        // Team URL: extract team info
        const [teamId, teamnameEncoded] = rest;
        const teamname = decodeURIComponent(teamnameEncoded).replace(/_/g, ' '); // "Harheimer_TC_(J11)" -> "Harheimer TC (J11)"
        result.teamId = teamId;
        result.teamname = teamname;
      } else {
        // Table URL: no team info
        result.teamId = null;
        result.teamname = null;
      }

      devLog('Parsed myTischtennis URL:', result);

      return result;
    } catch (error) {
      console.error('Error parsing myTischtennis URL:', error);
      throw error;
    }
  }

  /**
   * Decode group name from URL-encoded format
   * "2._Kreisklasse_Gr._2" -> "2. Kreisklasse Gr. 2"
   */
  decodeGroupName(encodedName) {
    // First decode URI components
    let decoded = decodeURIComponent(encodedName);
    
    // Replace underscores with spaces
    decoded = decoded.replace(/_/g, ' ');
    
    // Clean up multiple spaces
    decoded = decoded.replace(/\s+/g, ' ');
    
    return decoded.trim();
  }

  /**
   * Convert short season format to full format
   * "25/26" -> "2025/2026"
   * "24/25" -> "2024/2025"
   */
  convertToFullSeason(seasonShort) {
    const parts = seasonShort.split('/');
    if (parts.length !== 2) {
      return seasonShort;
    }

    const year1 = parseInt(parts[0]);
    const year2 = parseInt(parts[1]);

    // Determine century based on year1
    // If year1 < 50, assume 20xx, otherwise 19xx
    const century1 = year1 < 50 ? 2000 : 1900;
    const century2 = year2 < 50 ? 2000 : 1900;

    const fullYear1 = century1 + year1;
    const fullYear2 = century2 + year2;

    return `${fullYear1}/${fullYear2}`;
  }

  /**
   * Convert full season format to short format
   * "2025/2026" -> "25/26"
   * "2024/2025" -> "24/25"
   */
  convertToShortSeason(seasonFull) {
    const parts = seasonFull.split('/');
    if (parts.length !== 2) {
      return seasonFull;
    }

    const year1 = parseInt(parts[0]);
    const year2 = parseInt(parts[1]);

    const shortYear1 = String(year1).slice(-2);
    const shortYear2 = String(year2).slice(-2);

    return `${shortYear1}/${shortYear2}`;
  }

  /**
   * Fetch additional team data from myTischtennis
   * 
   * @param {Object} parsedUrl - Parsed URL data from parseUrl()
   * @param {string} cookie - Authentication cookie
   * @param {string} accessToken - Access token
   * @returns {Object} Additional team data
   */
  async fetchTeamData(parsedUrl, cookie, accessToken) {
    try {
      const { association, seasonShort, type, groupname, groupId, teamId, teamname } = parsedUrl;
      
      const seasonStr = seasonShort.replace('/', '--');
      const teamnameEncoded = encodeURIComponent(teamname.replace(/\s/g, '_'));
      
      // Build the API URL
      const apiUrl = `https://www.mytischtennis.de/click-tt/${association}/${seasonStr}/${type}/${encodeURIComponent(groupname)}/gruppe/${groupId}/mannschaft/${teamId}/${teamnameEncoded}/spielerbilanzen/gesamt?_data=routes%2Fclick-tt%2B%2F%24association%2B%2F%24season%2B%2F%24type%2B%2F%28%24groupname%29.gruppe.%24urlid_.mannschaft.%24teamid.%24teamname%2B%2Fspielerbilanzen.%24filter`;

      devLog(`Fetching team data from: ${apiUrl}`);

      const response = await fetch(apiUrl, {
        headers: {
          'Cookie': cookie || '',
          'Authorization': `Bearer ${accessToken}`,
          'Accept': 'application/json',
          'User-Agent': 'Mozilla/5.0'
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();

      // Extract additional information
      const teamData = {
        clubId: null,
        clubName: null,
        teamName: null,
        leagueName: null,
        leagueShortName: null,
        region: null,
        tableRank: null,
        matchesWon: null,
        matchesLost: null
      };

      if (data.data && data.data.head_infos) {
        const headInfos = data.data.head_infos;
        teamData.clubId = data.data.balancesheet?.[0]?.club_id || null;
        teamData.clubName = headInfos.club_name;
        teamData.teamName = headInfos.team_name;
        teamData.leagueName = headInfos.league_name;
        teamData.region = headInfos.region;
        teamData.tableRank = headInfos.team_table_rank;
        teamData.matchesWon = headInfos.team_matches_won;
        teamData.matchesLost = headInfos.team_matches_lost;
      }

      devLog('Fetched team data:', teamData);

      return {
        ...parsedUrl,
        ...teamData,
        fullData: data
      };
    } catch (error) {
      console.error('Error fetching team data:', error);
      throw error;
    }
  }

  /**
   * Complete configuration from URL
   * Combines URL parsing and data fetching
   * 
   * @param {string} url - The myTischtennis URL
   * @param {string} cookie - Authentication cookie (optional)
   * @param {string} accessToken - Access token (optional)
   * @returns {Object} Complete configuration data
   */
  async getCompleteConfig(url, cookie = null, accessToken = null) {
    const parsedUrl = this.parseUrl(url);
    
    if (cookie && accessToken) {
      return await this.fetchTeamData(parsedUrl, cookie, accessToken);
    }
    
    return parsedUrl;
  }

  /**
   * Validate if URL is a valid myTischtennis team URL
   * 
   * @param {string} url - The URL to validate
   * @returns {boolean} True if valid
   */
  isValidTeamUrl(url) {
    try {
      this.parseUrl(url);
      return true;
    } catch {
      return false;
    }
  }
  
  isValidUrl(url) {
    return this.isValidTeamUrl(url); // Alias for backward compatibility
  }

  /**
   * Build myTischtennis URL from components
   * 
   * @param {Object} config - Configuration object
   * @returns {string} The constructed URL
   */
  buildUrl(config) {
    const {
      association,
      season,
      type = 'ligen',
      groupname,
      groupId,
      teamId,
      teamname,
      urlType = 'team'
    } = config;

    // Convert full season to short format for URL
    const seasonShort = this.convertToShortSeason(season);
    const seasonStr = seasonShort.replace('/', '--');
    const groupnameEncoded = encodeURIComponent(groupname);

    if (urlType === 'table' || !teamId || !teamname) {
      // Build table URL
      return `https://www.mytischtennis.de/click-tt/${association}/${seasonStr}/${type}/${groupnameEncoded}/gruppe/${groupId}/tabelle/gesamt`;
    } else {
      // Build team URL
      const teamnameEncoded = encodeURIComponent(teamname.replace(/\s/g, '_'));
      return `https://www.mytischtennis.de/click-tt/${association}/${seasonStr}/${type}/${groupnameEncoded}/gruppe/${groupId}/mannschaft/${teamId}/${teamnameEncoded}/spielerbilanzen/gesamt`;
    }
  }
}

export default new MyTischtennisUrlParserService();
